Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SKAction not running on SKSpriteNode

The SKAction on my SKShapeNode isn't working, the code isn't getting executed, and the node isn't moving, even though the console is logging "Snake is moving". Is is because the node is a property of the SKScene and the actions are part of 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 used to work when they property was declared in the same function as the action

like image 290
Fayyouz Avatar asked Oct 25 '25 05:10

Fayyouz


1 Answers

myNode is a computed property. self.addChild(myNode) adds a node, but there is no myNode stored property.

myNode.run First computes a new node without adding it to the scene. Then it calls the run the action on it. but since it's a different node that is not on the scene, it will never run.

Change your myNode defintion to:

var myNode : SKShapeNode!

and in didMove(to view: add:

myNode = SKShapeNode(rectOf: snake.componentSize)
myNode.position = snake.head
myNode.fillColor = .red
like image 135
Steve Ives Avatar answered Oct 26 '25 18:10

Steve Ives