如何停止节点,让它在1秒后再次移动?

时间:2016-01-28 00:28:35

标签: ios swift sprite-kit skaction

我有一辆SKShapeNode车。它在移动。当我触摸它时,我想停止它1秒然后再回到运动状态。

我有这个代码...但它停止了,a3永远不会到达,汽车不会再开始移动

let a1 = SKAction.speedTo(0.0, duration: 0.0)
let a2 = SKAction.waitForDuration(0.5)
let a3 = SKAction.speedTo(1.0, duration: 0.0)

1 个答案:

答案 0 :(得分:0)

以下是如何将节点从A点移动到B点并在触摸时将其停止一秒的示例。

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        //Create a car
        let car = SKSpriteNode(color: UIColor.purpleColor(), size: CGSize(width: 40, height: 40))
        car.name = "car"
        car.zPosition = 1
        //Start - left edge of the screen
        car.position = CGPoint(x: CGRectGetMinX(frame), y:CGRectGetMidY(frame))
        //End = right edge of the screen
        let endPoint = CGPoint(x: CGRectGetMaxX(frame), y:CGRectGetMidY(frame))
        let move = SKAction.moveTo(endPoint, duration: 10)
        car.runAction(move, withKey: "moving")
        addChild(car)
    }

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

        let touch = touches.first
        if let location = touch?.locationInNode(self){

            //Get the node
            let node = nodeAtPoint(location)
            //Check if it's a car
            if node.name == "car" {

                //See if car is moving
                if node.actionForKey("moving") != nil{

                    //Get the action
                    let movingAction = node.actionForKey("moving")

                    //Pause the action (movement)
                    movingAction?.speed = 0.0

                    let wait = SKAction.waitForDuration(3)
                    let block = SKAction.runBlock({
                        //Unpause the action
                        movingAction?.speed = 1.0
                    })
                    let sequence = SKAction.sequence([wait, block ])
                    node.runAction(sequence, withKey: "waiting")
                }
            }
        }
    }
}

一切都被评论了。所以基本上,这里发生的是:

  • 节点移动是通过与&#34;移动&#34;相关联的操作完成的。键
  • 当用户触摸节点时,&#34;移动&#34;密钥暂停;当这种情况发生时,另一个叫做&#34;等待&#34;并开始&#34;并行#34;
  • &#34;等待&#34;动作等待一秒钟,并取消暂停&#34;移动&#34;行动;因此汽车继续运动

目前,当汽车被触及时,&#34;移动&#34;动作暂停...因此,如果你再次触摸汽车,它将保持额外的秒数(新的&#34;等待&#34;动作将覆盖先前的&#34;等待&#34;动作)。如果您不想要这种行为,可以检查汽车是否已经等待,如下所示:

if node.actionForKey("waiting") == nil {/*handle touch*/}

或者您可以通过检查&#34;移动&#34;相关联的操作的速度属性值来检查汽车是否已停止。键。