How to make an SKSprite node move side to side on its own when game starts?

740 views Asked by At

I'm making a swift game with spritekit where I just added an image to the scene that's an SKSpriteNode. When the game starts, I want to make it move just on the x-axis from the left side of the screen to the right side, repeating forever. I'm struggling with what the code should be for this.

The code for my image is:

func addDrake1(){
    let Drake1 = SKSpriteNode(imageNamed: "Drake1")
    Drake1.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height - 300)
    Drake1.zPosition = 2
    addChild(Drake1)
}
1

There are 1 answers

4
Daniel Mihaila On

if you start your sprite position from the far left at cgpoint(x: 0, y: frame.size.height - 300)

you could use this method :

func moveSprite() {

        let moveRight = SKAction.moveByX(frame.size.width, y: 0, duration: 2)

        let moveLeft = SKAction.moveByX(-frame.size.width, y: 0, duration: 2)


        let moveBackAndForth = SKAction.repeatActionForever(SKAction.sequence([moveRight, moveLeft]))


        Drake1.runAction(moveBackAndForth)

     }   

you could also change the speed at which the sprite moves by changing the duration in the actions moveLeft and moveRight