【问题标题】:Modify property on SKNode while moving移动时修改 SKNode 上的属性
【发布时间】:2017-10-02 22:23:48
【问题描述】:

我有一个 SKNode 的子类,它充当我的“生物”。这些使用 SKActions 自动在场景中移动。我有兴趣在生物移动时修改(减少)“能量”属性(Int)。

不能保证该生物移动整个移动 SKAction 的长度(它可以被打断),因此计算总距离然后在它开始移动时立即减少属性并不理想。我基本上想说“节点每移动 1 秒,降低能量属性”。

我该怎么做?我不知所措!谢谢。

【问题讨论】:

    标签: ios swift sprite-kit sknode


    【解决方案1】:

    在您的GameScene.swift 类中,您有一个update(deltaTime seconds: TimeInterval) 函数,可以跟踪一秒的时间间隔。添加一个类级别的变量来保存累计时间,然后每隔一秒检查一次你的生物是否正在运行它的动作。

    class GameScene : SKScene {
        private var accumulatedTime: TimeInterval = 0
    
        override func update(_ currentTime: TimeInterval) {    
            if (self.accumulatedTime == 0) {
                self.accumulatedTime = currentTime
            }
    
            if currentTime - self.accumulatedTime > 1 {
                if creatureNode.action(forKey: "moveActionKey") != nil {
                   // TODO: Update energy status
                }
    
                // Reset counter
                self.accumulatedTime = currentTime
            }
        }
    }
    

    【讨论】:

    • 如果您将时间间隔设为变量,那么您也可以即时调整它:let energyUpdateTime : TimeInterval = 1 然后if currentTime - self.accumulatedTime > energyUpdateTime
    【解决方案2】:

    如果您知道能量属性,那么只需将其用作您的持续时间,并使用move(by:SKAction。

    如果你想让你的能量耗尽,请在群组中使用SKAction.customAction 来消耗它

    var previousTime = 0
    let move = SKAction.moveBy(x:dx * energy,y:dy * energy,duration:energy)
    let depreciateEnergy = SKAction.customAction(withDuration:energy,{(node,time) in node.energy -= (time - previuosTime);previousTime = time}) 
    let group = [move,depreciateEnergy]
    character.run(group,withKey:"character")
    

    现在,如果您在任何时候需要停止操作,只需致电character.removeActionForKey("character"),您的能量计将保持剩余电量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2021-11-25
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多