There are two problems with your code. Firstly, to get kDefaultXToMovePerSecond
change, the following syntax must be used: kDefaultXToMovePerSecond += 10
, and not kDefaultXToMovePerSecond + 10
. I am not sure why the second way of doing it, the one that you have in your code, is not caught by the compiler as it is not assigning this value to any variable. But I have tested this syntax in playground and the value of the variable does not change with this syntax. Secondly, though you create the action to move the sprite, it is never updated and therefore the sprites speed will never change. This is because by simply changing the kDefaultXToMovePerSecond
variable in touchesBegan
, you are merely changing the variable itself, but not the parameter value in the SKAction
which is not connected to it. There are two options to create the behavior you are looking for.
- Add a new
SKAction
to the sprite every time the touchesBegan
is called. This new action will override the previous one.
- Remove the previous action on the sprite and then add a new one every time
touchesBegan
is called. Though the effect of this is the same as option 1, it has the benefit of deallocating the SKActions
that you have created. This prevents them from piling up, never to be used again, which takes up unnecessary memory.
In case you would like guidance on how to accomplish this, refer to the following code that I wrote and tested in the Xcode 7 Beta simulator.
class GameScene: SKScene {
let player = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 100, height: 50))
var kDefaultXToMovePerSecond: CGFloat = 0
override func didMoveToView(view: SKView) {
player.position = CGPoint(x: 100, y: 200)
addChild(player)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
//Make sure that it is the same kay as below
player.removeActionForKey("anyKeyWillDo")
kDefaultXToMovePerSecond += 10
let moveLeft = SKAction.moveByX(kDefaultXToMovePerSecond, y: 0, duration: 0.7)
player.runAction(SKAction.repeatActionForever(moveLeft), withKey: "anyKeyWillDo")
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
Note: In order to implement option 1, take out the player.removeActionForKey("anyKeyWillDo")
line. For option 2, leave it in.