SKAction not working on SKSpriteNode
SKAction
on mine SKShapeNode
doesn't work, code doesn't execute and node doesn't move even if console logs "Snake is moving". Is it because node is an SKScene property and the actions are part of the lower scope functions?
class LevelScene: SKScene, SnakeShower {
var snake: Snake {
let theSnake = Snake(inWorld: self.size)
return theSnake
}
override func didMove(to view: SKView) {
self.backgroundColor = .green
snake.delegate = self
}
var myNode: SKShapeNode {
let node = SKShapeNode(rectOf: snake.componentSize)
node.position = snake.head
node.fillColor = .red
return node
}
func presentSnake() { // function called by the snake in the delegate (self)
self.addChild(myNode)
startMoving()
}
func startMoving() {
print("snake is moving")
myNode.run(SKAction.repeatForever(SKAction.sequence([
SKAction.move(by: self.snake.direction.getVector(), duration: 0.2),
SKAction.run({
if self.myNode.position.y > (self.size.height / 2 - self.snake.componentSize.height / 2) {
self.myNode.removeAllActions()
}
})
])))
}
}
It worked when the property was declared in the same function as the action
source to share
myNode
is a computed property. self.addChild(myNode)
adds node, but no stored property myNode
.
myNode.run
Computes the new node first without adding it to the scene. Then it calls an action on it. but since it is different from a node that is not on stage it will never work.
Change the setting myNode
to:
var myNode : SKShapeNode!
and in didMove(to view:
add:
myNode = SKShapeNode(rectOf: snake.componentSize)
myNode.position = snake.head
myNode.fillColor = .red
source to share