是否可以在运行SKAction的过程中更改SKNode的位置?

时间:2016-06-19 15:42:19

标签: swift sprite-kit skaction

这是我尝试做上面描述的事情,但它不起作用:

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
    addChild(square)
    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) {
    print(square.position.x)
    if (square.position.x > 45) && (square.position.x < 50) {
        isConditionMet = true
    }
    checkThenChangePosition(square)
}

根据上面的代码,我希望广场从(0,0)开始向(100,100)方向行驶。一旦正方形的位置在45到50之间(通常在45.5左右,因为SKAction不会将整数值移动平方),正方形应该从当前的x位置变为size.width的值(在iPhone 6上)模拟器它是375.0)。

然而,事实并非如此。相反,在SKAction完成之前(方块已达到(100,100)),方块不会移动到x = 375.0。有没有办法在运行SKAction的过程中进行方形更改位置,然后继续运行SKAction。基本上我希望正方形从x = 0到45&lt; x&lt; 50,然后传送到x = 375,然后从x = 375到x = 100旅行。提前感谢。

1 个答案:

答案 0 :(得分:0)

您必须在应用新操作之前停止操作

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

    square.runAction(moveSquare)

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

专门针对您的案例

func checkThenChangePosition(shape:SKShapeNode) {
        if isConditionMet == true {
            shape.removeAllActions()
            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
            shape.runAction(moveSquare)
        }
    }