David Sundström David Sundström - 4 months ago 20
Swift Question

Move sprite forever

I am trying to move sprite to the right when I press a button on the screen. However, when I try doing it I only have a solution to move the sprite to a certain point. So... I want the sprite to move to the right forever or until i do something else.

This is in Xcode using Swift in SpriteKit.

` override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

for touch : AnyObject in touches{

let pointInTouch = touch.locationInNode(self)
let tappedNode = nodeAtPoint(pointInTouch)
let tappeNodeName = tappedNode.name

if tappeNodeName == "Btn"{

player.physicsBody?.velocity = CGVectorMake(0, 0)

let action = SKAction.applyImpulse(CGVectorMake(400, 0), duration: 1)
player.runAction(SKAction.repeatActionForever(action))

print("Touched!")

}

}

Answer

You can simply move your node to the right untill it does exist the scene

class GameScene: SKScene {

    private var player: SKSpriteNode!

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        guard let touch = touches.first else { return }
        let pointInTouch = touch.locationInNode(self)
        let tappedNode = nodeAtPoint(pointInTouch)
        if tappedNode.name == "Btn"{
            let moveToRight = SKAction.moveToX(self.frame.width + player.frame.width, duration: 5)
            player.runAction(moveToRight)
        }

    }
}