gpt4 book ai didi

ios - 通过触摸在枚举状态之间切换

转载 作者:行者123 更新时间:2023-11-28 13:19:45 25 4
gpt4 key购买 nike

我有一个像这样的简单播放器类:

enum State: Int {

case dead, alive, idle

}

class Player {

var playerSprite : SKSpriteNode
var currentState : State


init(passedInState: State) {

currentState = passedInState
self.playerSprite = SKSpriteNode(imageNamed: "playersprite.png")

switch currentState {

case .dead:
println("Player is dead")

case .alive:
println("Player is alive")

}

}
}

在我的主类中,我创建了一个 Player 类的实例,并尝试通过在 touch 方法中点击它来更改玩家状态,如下所示:

class GameScene: SKScene {
override func didMoveToView(view: SKView) {

let player1 = Player(passedInState: .alive)
self.addChild(player1.playerSprite)
player1.playerSprite.position = CGPointMake(100, 100)
}


override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
for touch in touches {

let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(self)
var locationSprites = nodesAtPoint(location)

for bla in locationSprites {

(bla as Player).currentState = .dead

}
}
}

我在触摸 Sprite 时总是崩溃。你知道为什么吗?

最佳答案

似乎有一个沮丧的失败,在你的代码中我看到有 2 个强制的 donwcasts:

let touch = touches.anyObject() as UITouch

(bla as Player).currentState = .dead

我假设错误在最后一个,所以我建议设置一个断点并检查 bla 以检查它是否实际上是 Player 的实例。根据您的逻辑,如果它可能不是 Player 的实例,我建议使用可选的向下转换:

if let player = bla as? Player {
player.currentState = .dead
}

优点是如果 bla 不是 Player 的实例,则不会执行 if block ,而不是使应用程序崩溃。


评论跟进

如果想在播放器状态变化时做一些自定义处理,可以在Player类的currentState属性中添加一个属性观察器:

var currentState : State {
didSet {
switch currentState {
case .dead:
println("Player is dead")

case .alive:
println("Player is alive")

case .idle:
break
}
}
}

关于ios - 通过触摸在枚举状态之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26929118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com