Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing actions in order (not asynchronously) on different nodes

Here is an illustration of what I am trying to do:

enter image description here

Here is my code so far:

import SpriteKit

class GameScene: SKScene {
    let mySquare1 = SKShapeNode(rectOfSize:CGSize(width: 50, height: 50))
    let mySquare2 = SKShapeNode(rectOfSize:CGSize(width: 50, height: 50))

    override func didMoveToView(view: SKView) {
        mySquare1.position = CGPoint(x: 100, y:100)
        mySquare2.position = CGPoint(x: 300, y:100)

        mySquare1.fillColor = SKColor.blueColor()
        mySquare2.fillColor = SKColor.blueColor()

        self.addChild(mySquare1)
        self.addChild(mySquare2)

        let moveAction1 = SKAction.moveTo(CGPoint(x:250, y:100), duration: 1)
        mySquare1.runAction(moveAction1)

        let moveAction2 = SKAction.moveTo(CGPoint(x:300, y:350), duration: 1)
        mySquare2.runAction(moveAction2)
    }

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

    }

    override func update(currentTime: CFTimeInterval) {

    }
}

My problem is, I am trying to move the rectangles synchronously (not asynchronously). That is, I want my first rectangle start moving, finish its movement, stop. And then, start my second rectangle moving, finish its movement and stop.

Currently what happens is that, when I run my program, they both start moving at the same time.

I also found SKAction.sequence for actions to play in order, however, I only can use this for actions on the same object. Not in different objects like in my example.

like image 408
Sait Avatar asked Dec 14 '22 04:12

Sait


1 Answers

If you want to move the two rectangles sequentially (not in parallel), you could use the completion property of the first action like this (apple docs):

import SpriteKit
class GameScene: SKScene {
    let mySquare1 = SKShapeNode(rectOfSize:CGSize(width: 50, height: 50))
    let mySquare2 = SKShapeNode(rectOfSize:CGSize(width: 50, height: 50))
    override func didMoveToView(view: SKView) {
        mySquare1.position = CGPoint(x: 100, y:100)
        mySquare2.position = CGPoint(x: 300, y:100)
        mySquare1.fillColor = SKColor.blueColor()
        mySquare2.fillColor = SKColor.blueColor()
        self.addChild(mySquare1)
        self.addChild(mySquare2)
        let move1 = SKAction.moveToX(250, duration: 1.0)
        let move2 = SKAction.moveToY(250, duration: 1.0)
        self.mySquare1.runAction(move1,completion: {
            self.mySquare2.runAction(move2)
        })
    }
}
like image 57
Alessandro Ornano Avatar answered Dec 27 '22 10:12

Alessandro Ornano