Rae Tucker
Rae Tucker

Reputation: 523

How do I make a sprite change directions when tapped?

When first touched, my player starts moving up the y axis and I have it set up like so:

 override func touchesBegan(...) {
if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
         player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
 }
    isMovingup = !isMovingup
    }

However, when the node is tapped a second time, Id like it to move down the y axis but as of now, it just does nothing. Will post more code if necessary.

Upvotes: 2

Views: 164

Answers (3)

Knight0fDragon
Knight0fDragon

Reputation: 16827

you need to stop the previous action with player.removeAllActions() otherwise your actions will keep stacking.

override func touchesBegan(...) {
    player.removeAllActions() //<-- Touching always causes the player to change direction, so lets cancel out the previous action before assigning a new one
    if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
    }
    isMovingup = !isMovingup
}

Upvotes: 2

VictorVH
VictorVH

Reputation: 327

It seems to be that the code piece

isMovingup = !isMovingup

Is defined outside of the function, so it is not being run. Move it inside the function after the else statement so it will be run everytime you call the function

override func touchesBegan(...) {
    if isMovingup == true  {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
   }
   isMovingup = !isMovingup
}

Upvotes: 1

dfrib
dfrib

Reputation: 73176

It looks as if your boolean flip is outside the scope of the function. Try moving the line isMovingup = !isMovingup to inside the last curly brace.

override func touchesBegan(...) {
    if isMovingup {
        let up = SKAction.moveByX(0, y: 900, duration: 9)
        player.runAction(up)
    }
    else {
        let down = SKAction.moveByX(0, y: -900, duration: 9)
        player.runAction(down)
    }
    isMovingup = !isMovingup
}

Upvotes: 2

Related Questions