繁体   English   中英

如何控制SpriteKit中的节点速度

[英]How to control the speed of nodes in SpriteKit

我有一堆对象( SKNode )从屏幕顶部开始“下降”到底部,通过SKAction.move(to:duration:)node.run(moveAction) 此外,我在屏幕中央有一个节点,它有自己的物理主体,可以通过触摸输入左右拖动。 我可以很好地检测到碰撞,但我想知道在中心节点与任何对象接触时是否存在“暂停”所有对象的范例。 另外,我希望能够移动中心节点而其他对象被“暂停”,这样我就可以将它移开,然后让对象恢复运动。 我想我可以遍历所有现有对象并设置它们的isPaused属性,但我不确定应用程序如何知道中心节点何时不再“碰撞”,以便我可以切换回属性。

要暂停一些事情,你必须检测didBegin()的联系人,在一些数组中添加应该暂停的节点,最后暂停节点。 例如,实际的暂停可以在didSimulatePhysics()完成。 暂停所有可以使用的节点

 self.enumerateChildNodesWithName("aName") {
    node, stop in 
    // do something with node or stop
}

或者使用节点的属性并循环遍历它(例如,循环遍历应该暂停的节点的容器)。

您还可以暂停某些操作:

if let action = square.actionForKey("aKey") {

        action.speed = 0       
}

使用action.speed = 1取消暂停,或者使用action.speed = 0.5使其缓慢移动

为了减慢物理模拟,有一个名为physicsWorld.speed的属性(确定模拟运行的速率)。

哦,男孩,事情肯定会变得复杂。 Whirlwind所说的每件事都是正确的,但是迭代遍历场景中的每个节点都会变得很麻烦。

相反,我建议为SKNode创建一个特殊的子类。 由于苹果框架导致的错误,现在需要这个特殊的类

class UserPausableNode : SKNode
{
    public var userPaused = false
    {
        didSet
        {
            super.isPaused = userPaused
        }
    }
    override var isPaused : Bool
        {
        get
        {
            return userPaused
        }
        set
        {
            //Yes, do nothing here
        }
    }
}

我们需要这样做的原因是因为无论何时调用isPaused,它都会迭代到所有子isPaused并设置子isPaused属性。

当场景暂停和取消暂停时,这会成为一个问题,因为它会改变孩子的暂停状态,这是我们不想做的。

此类可防止isPaused变量发生更改。

既然这个类存在,我们想要做的是将它添加到场景中,并将所有移动节点添加到这个新节点。

由于所有节点都在这个新节点上,我们需要做的就是将userPaused设置为true,这将停止所有节点。

现在确保您正在移动的节点不是此分支的一部分,它应该在外面以便您可以移动它。

class GameScene : SKScene
{
    var userBranch = UserPausableNode()

    func didMove(to view:SKView)
    { 
        self.addChild(userBranch)
        //generetedChildren are nodes that you create that you plan on pausing as a group 
        for generatedChild in generatedChildren
        {
            userBranch.addChild(node)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       //this will pause and unpause based on opposite of previous state
        userBranch.userPaused = !userBranch.userPaused
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM