RPatel99 RPatel99 - 8 months ago 29
Swift Question

Is it possible to change the position of an SKNode while it is in the middle of running an SKAction?

Here is my attempt at doing what I described above, but it didn't work:

let square = SKShapeNode(rectOfSize: CGSize(width:60, height: 80))
var isConditionMet = false

override func didMoveToView(view: SKView) {
square.position.x = 0
square.position.y = 0
var moveSquare:SKAction
moveSquare = SKAction.moveTo(CGPoint(x: 100, y: 100), duration: NSTimeInterval(5))
square.runAction(SKAction.sequence([moveSquare, SKAction.removeFromParent()]))

func checkThenChangePosition(shape:SKShapeNode) {
if isConditionMet == true {
shape.position.x = size.width

override func update(currentTime: CFTimeInterval) {
if (square.position.x > 45) && (square.position.x < 50) {
isConditionMet = true

With the code above, I hoped that the square would start at (0,0) and travel towards (100,100). Once the square's position is between 45 and 50 (usually at around 45.5 because the SKAction does not move the square by integer values), the square should change from its current x position to whatever the value is of size.width (on an iPhone 6 simulator it was 375.0).

However, that is not what happened. Instead, the square does not move to x = 375.0 until the SKAction is completed (once the square has reached (100,100)). Is there any way to make the square change position in the middle of running the SKAction and then continue running the SKAction. Basically I would want the square to travel from x = 0 to 45 < x < 50, then teleport to x = 375, then travel from x = 375 to x = 100. Thanks in advance.


You will have to stop the action before applying the new action

    let destination = CGPoint(x: 100, y: 100)
    let moveSquare = SKAction.moveTo(destination, duration: NSTimeInterval(3))


    self.runAction(SKAction.sequence([SKAction.waitForDuration(1.0), SKAction.runBlock( {
        self.square.position = CGPoint(x: 300, y: 300)
    } )]))

specifically for your case

func checkThenChangePosition(shape:SKShapeNode) {
        if isConditionMet == true {
            shape.position.x = self.size.width
            //rerun action to send shape to original location
            //you will have to give this object access to moveSquare either pass it along or make it globally accessible
            //another thing to consider is that the duration may need to be adjusted to keep the speed of the shape consistent