Reputation: 884
While a player is touching, the code below is suppose to move a node to the MaxX
. Once they hit that point it is suppose to redirect the node's movement towards the MinX
and vice versus.
As it stands right now, I can only move the player in once direction and it is ignoring the movePlayer()
logic.
Action Declarations
var moveRightTest:Bool = true;
var moveLeftTest:Bool = false;
let moveRight = SKAction.moveByX(1000, y: 0, duration: 2);
let moveLeft = SKAction.moveByX(-1000, y: 0, duration: 2);
Inside the GameScene:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
movePlayer();
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
stopPlayer();
}
func movePlayer() {
if(moveRightTest == true) {
if(player.position.x <= CGRectGetMaxX(self.frame)) {
player.runAction(moveRight);
} else {
moveRightTest = false;
moveLeftTest = true;
}
}
else if(moveLeftTest == true) {
if(player.position.x >= CGRectGetMinX(self.frame)) {
player.runAction(moveLeft);
} else {
moveLeftTest = false;
moveRightTest = true;
}
}
}
func stopPlayer() {
player.removeAllActions();
}
Note: I subbed out some vars with ints/floats to remove the calculation from the code in order to present. Its not related to the issue. Im also just learning Swift.
Upvotes: 0
Views: 70
Reputation: 3405
Now your function movePlayer
is performed only once when you're calling it, so the player comes to the right edge and stops. You need to repeat it after each run the following steps. To do this, you can use runAction
with completion
like this:
isRight: Bool = true
let moveRight = SKAction.moveToX(CGRectGetMaxX(self.frame), duration: 2)
let moveLeft = SKAction.moveToX(CGRectGetMinX(self.frame), duration: 2)
func movePlayer() {
if isRight {
player.runAction(moveRight, completion: { () -> Void in
isRight = false
self.movePlayer()
})
} else {
player.runAction(moveLeft, completion: { () -> Void in
isRight = true
self.movePlayer()
})
}
}
Upvotes: 1