Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a sprite move up and down forever in swift SpriteKit

I am trying to make a sprite move up and down forever, I have tried using an "if statement" which checks if the position is... than it will move up again. But it does not work. I would really appreciate some help, thanks! Here is the code.

var Ground = SKSpriteNode()
var Ground2 = SKSpriteNode()

override func didMoveToView(view: SKView) {
    Move()
}

func Move(){
    let action = SKAction.moveToY(self.frame.height / 2 - 360, duration: 5.0)
    Ground.runAction(SKAction.repeatActionForever(action))

    let action2 = SKAction.moveToY(self.frame.height / 2 + 140, duration: 5.0)
    Ground2.runAction(SKAction.repeatActionForever(action2))
}
like image 517
David Sundström Avatar asked Dec 20 '15 16:12

David Sundström


2 Answers

You can use action sequence for this:

override func didMoveToView(view: SKView) {

    let sprite = SKSpriteNode(color: SKColor.purpleColor(), size: CGSize(width: 100, height: 10))

    sprite.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))

    addChild(sprite)

    let moveUp = SKAction.moveByX(0, y: 200, duration: 2)

    let sequence = SKAction.sequence([moveUp, moveUp.reversedAction()])

    sprite.runAction(SKAction.repeatActionForever(sequence), withKey:  "moving")
}
like image 99
Whirlwind Avatar answered Oct 14 '22 09:10

Whirlwind


Whirlwind's answer updated to Swift 5

        let sprite = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 10))

        sprite.position = CGPoint(x: frame.midX, y: frame.midY)

        addChild(sprite)

        let moveUp = SKAction.moveBy(x: 0, y: 200, duration: 2)

        let sequence = SKAction.sequence([moveUp, moveUp.reversed()])

        sprite.run(SKAction.repeatForever(sequence), withKey:  "moving")
like image 1
uplearned.com Avatar answered Oct 14 '22 07:10

uplearned.com