Modify property on SKNode while moving

穿精又带淫゛_ 提交于 2019-12-01 12:26:36

问题


I have a subclass of SKNode that acts as my "creature". These move about the scene automatically using SKActions. I'm interested in modifying (decreasing) an 'energy' property (Int) as the creature moves.

The creature isn't guaranteed to move the entire length of the move SKAction (it can be interrupted), so calculating the total distance and then decreasing the property as soon as it starts moving isn't ideal. I'd essentially like to say "for every 1 second the node is moving, decrease the energy property".

How can I do this? I'm at a loss! Thank you.


回答1:


In your GameScene.swift class you have an update(deltaTime seconds: TimeInterval) function that can track one second intervals. Add a class level variable to hold the accumulated time, then check every one second if your creature is running its action.

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
        }
    }
}



回答2:


If you know the energy property, then just use that as your duration, and use the move(by: SKAction.

If you want your energy to deplete with it, use an SKAction.customAction in a group to decreate it

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")

Now if at any time you need to stop the action, just call character.removeActionForKey("character"), and your energy meter will stay at whatever energy is remaining.



来源:https://stackoverflow.com/questions/46534588/modify-property-on-sknode-while-moving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!