3
votes

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

2
what do you mean by 'isn't working' - what exactly happens?Steve Ives
@SteveIves Edited.Fayyouz
I would say (from a brief look ) that he is working on a wrong node. He first create a node and add it, then gets another node and try to run an action on it, but the node is not in a node tree.Whirlwind
@Whirlwind. I think you're right. myNode is a computed property. self.addChild(myNode) adds a node, but there is no myNode property. Then myNode.run computes a new node but doesn't add it to the scene before trying to run the action on it. but it's a different node anyway.Steve Ives
@Fayyouz Actually, you don't have a single node called myNode. You have a computed property myNode that every time it is referenced, returns a new, distinct SKShapeNode.Steve Ives

2 Answers

8
votes

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
2
votes

I had an issue almost identical to this, where I had unresponsive child nodes in a referenced node. Turns out that referenced nodes default to isPaused being true (answer thread found here)

The solution was to change the isPaused property to false.

referencedNode.isPaused = false