我有一个像这样简单的玩家类:
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类的实例,并尝试通过触摸方法点击它来改变玩家状态,如下所示:
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时我总是遇到崩溃。你知道为什么吗?
答案 0 :(得分:2)
似乎有一个沮丧的失败,在你的代码中,我看到有两个被迫的弃儿:
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块不会被执行,而不是让应用程序崩溃。
评论跟进
如果您想在播放器状态更改时进行一些自定义处理,可以将属性观察者添加到currentState
类的Player
属性中:
var currentState : State {
didSet {
switch currentState {
case .dead:
println("Player is dead")
case .alive:
println("Player is alive")
case .idle:
break
}
}
}