Search code examples
swiftsprite-kitskspritenodeskphysicsbody

Increase Node Speed with SKPhysicsBody linearDamping Swift 4


I have the below class being called from my GameScene

func update(_ currentTime: TimeInterval)

Since it's being called there, my class is being called every second which leads me to this. I currently have my self.physicsBody?.linearDamping = 0.6 but how would I increase that number so I can also increase the speed? I was going to use another Timer till I realized my SKSpriteNode class is being called every second. Not too sure how to go about this, any ideas? I basically want to decrease that number every 2.0 seconds without letting the update function get in the way.


Solution

  • Any time you want to do something at regular time intervals in a sprite-Kit game, you can implement this as follows:

    First declare 2 properties (in your class but outside all the function definitions)

    var timeOfLastThing: CFTimeInterval = 0.0
    var timePerThing: CFTimeInterval = 2.0    // How often to do the thing
    

    ( if the thing you want to do every 2 seconds is spawn a monster, then you might call these timeOfLastMonsterSpawn and timePerMonsterSpawn, but it's up to you)

    Then, in Update, check to see if the timePerThing has been exceeded. If so, call your doThing function which does what you need it to and then reset the time since the last call:

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
        if (currentTime - timeOfLastThing > timePerThing) {
           doThing()
           self.timeOfLastThing = currentTime
        }
    }
    
    func doThing() {
           // Your spawn code here
    }
    

    The advantage of making the doThing a separate function (as opposed to it being in line in update())is that you can call it from didMoveToView or any other place to spawn objects outside of the normal time-controlled cycle.

    You can change the value of timePerThing as necessary to control the rate at which things happen.

    You could also look into creating an SKAction that runs doThing at specified time intervals, but I think to change the rate at which objects are spawned, you'll have to delete and re-create the SKAction, which you could do this in a setter for timePerThing.

    You shouldn't really use NSTimer in SpriteKit, as the SpriteKit engine will be unaware of what the timer is doing and can't control it (one example is that the timer keeps running and doing stuff even if you set the scene to paused).