gfgruvin
gfgruvin

Reputation: 495

X, Y coordinates of SKSpriteNode do not change after the node has been moved

I have the following code to move a SKSpriteNode from a position off-screen to a position on-screen. spawnNode creates the node with a starting position off-screen. The nodePositions is an array of struct containing x, y and Zposition points on-screen. The code does move the node to the position that I want. However, I want to use the current node position to later position more nodes. The print statements show the same result. Pre & Post are the same. This makes no sense to me. Can anyone explain this to me? It looks like may have to make the successive node's children. I didn't want to do this.

    spawnNode()
    allNodes[0].texture = SKTexture(imageNamed: imageName)

    print("Pre: x: \(String(describing: allNodes[0].position.x))")
    print("Pre: y: \(String(describing: allNodes[0].position.y))")

    let duration: CGFloat = 0.5
    moveNodePos = SKAction.moveBy(x: nodePositions[0].posX, y: nodePositions[0].posY, duration: TimeInterval(duration))
    moveNodePos.timingMode = .easeIn
    allNodes[0].zPosition = nodePositions[0].zPosition
    allNodes[0].run(moveNodePos)
    print("Post: x: \(String(describing: allNodes[0].position.x))")
    print("Post: y: \(String(describing: allNodes[0].position.y))")

Pre: x: 0.0 Pre: y: 500.0 Post: x: 0.0 Post: y: 500.0

Upvotes: 1

Views: 33

Answers (2)

JohnV
JohnV

Reputation: 990

The SKAction moves the node over a duration of 0.5 seconds. The line allNodes[0].run(moveNodePos) is executed, the moveBy action starts, and the code following it (i.e. the print statements) are executed immediately. This means when you execute the print statements, the action still has not completed and the node is not yet moved. Try printing the position of the node after the action completes, e.g. using

allNodes[0].run(moveNodePos, completion: { insert the print statements here } )

Hope this helps!

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 385500

An SKAction happens over time, as the program repeatedly passes through the rendering loop.

Since the program doesn’t pass through the rendering loop between your allNodes[0].run(moveNodePos) run statement and the following print statements, the action hasn’t had an opportunity to modify the node’s position by the time of the print statements.

Upvotes: 0

Related Questions