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))
}
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")
}
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With