1

I have a timer that spawns another enemy every second. I want it so that based on the score that the user has the time between spawning new enemies decreases. Basically, the higher the score the more thee enemies. Here is my current timer code.

    EnemyTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("enemies"), userInfo: nil, repeats: true)
ThomasW
  • 16,981
  • 4
  • 79
  • 106
jhamer123
  • 19
  • 6
  • I have tried using a var speeds = 0 and such but i get an error saying, Cannot convert value of type 'Int' to expected argument type 'NSTimeInterval' (aka 'Double'). thanks a lot – jhamer123 Oct 14 '15 at 20:31
  • `var speed : Double = 0` – R Menke Oct 14 '15 at 20:54
  • @jhamer123 Read this http://stackoverflow.com/a/23978854/3402095 It could save you from some problems in the future. If you wonder about which problems you can run into, take a look at this : http://stackoverflow.com/q/33052867/3402095 – Whirlwind Oct 14 '15 at 21:55

2 Answers2

0

All you need to do is make sure you use 2 or more decimal places eg: you want it to spawn faster than 1 second so..

let newSpeed = 0.75
EnemyTimer = NSTimer.scheduledTimerWithTimeInterval(newSpeed, target: self, selector: Selector("enemies"), userInfo: nil, repeats: true)

this will make them spawn every .75 seconds. Just make sure if you use whole number you do 1.0 not just 1 otherwise yes you will get the error Cannot convert value of type 'Int' to expected argument type 'NSTimeInterval' (aka 'Double')

Eli
  • 668
  • 2
  • 13
  • 37
0

Instead of a timer, you can use the update function of the SKScene to spawn enemies at variable intervals. For example

var previousTime : NSTimeInterval = -1
let score = 100


func spawnEnemy() {
    print("Spawning Enemy")
}

override func update(currentTime: NSTimeInterval) {

    var spawnTimeInterval : NSTimeInterval = 1 - (NSTimeInterval(score)/1000) 

    let minSpawnTime : NSTimeInterval = 0.1

    if spawnTimeInterval < minSpawnTime {
        spawnTimeInterval = minSpawnTime
    }


    if previousTime != -1 {

        let elapsedTimeInterval = currentTime - previousTime
        if elapsedTimeInterval > spawnTimeInterval {

            spawnEnemy()
            previousTime = currentTime
        }

    } else {
        previousTime = currentTime;
    }

}

In the above code, the each 100 points will reduce 0.1 seconds from the spawnTimeInterval. You can change this calculation as per your requirements.

rakeshbs
  • 24,392
  • 7
  • 73
  • 63