I'm a newbie to programming so please help. I'm trying to set up intervals to create various Sprite nodes throughout my game (using the update function). However, each Sprite node needs to spawn at different intervals. I have a bunch of "if" statements and it seems to be causing my frame rate to drop and cause the app to lag. Can someone please tell me how to fix this? If possible, please also explain to me why it does this so that I can better understand the coding process. Thank you!
var timeBetweenBirds: Int!
var timeBetweenBadBirds: Int!
var timeBetweenSubtractTimeBirds: Int!
var timeBetweenAddTimeBirds: Int!
var timeBetweenBonusBirds: Int!
var now : NSDate?
var nextTime : NSDate?
var badBirdNextTime: NSDate?
var subtractTimeBirdNextTime: NSDate?
var addTimeBirdNextTime: NSDate?
var bonusBirdNextTime: NSDate?
override func update(currentTime: CFTimeInterval) {
timeBetweenBirds = Int(arc4random_uniform(3))
timeBetweenBadBirds = Int(arc4random_uniform(3) + 2)
timeBetweenSubtractTimeBirds = Int(arc4random_uniform(3) + 2)
timeBetweenAddTimeBirds = Int(arc4random_uniform(1) + 5)
timeBetweenBonusBirds = Int(arc4random_uniform(20) + 20)
now = NSDate()
if now?.timeIntervalSince1970 > nextTime?.timeIntervalSince1970 {
nextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBirds))
createBird()
}
if now?.timeIntervalSince1970 > badBirdNextTime?.timeIntervalSince1970 {
badBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBadBirds))
createBadBird()
}
if now?.timeIntervalSince1970 > subtractTimeBirdNextTime?.timeIntervalSince1970 {
subtractTimeBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenSubtractTimeBirds))
createSubtractTimeBird()
}
if now?.timeIntervalSince1970 > addTimeBirdNextTime?.timeIntervalSince1970 {
addTimeBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenAddTimeBirds))
createAddTimeBird()
}
if now?.timeIntervalSince1970 > bonusBirdNextTime?.timeIntervalSince1970 {
bonusBirdNextTime = now?.dateByAddingTimeInterval(NSTimeInterval(timeBetweenBonusBirds))
createBonusBird()
}
Maybe this is not the correct solution, but it'll simplify things at least.
A couple of things to consider.
Right now you are generating a new
timeBetweenBirdsvalue in eachupdateloop, but you're only using it if you end up in theifstatementSo a place to start could be to update the
timeBetweenBirdsvalue only when needed.As I see it, you don't need to create all these dates and compare between them.
Every time
updateis called, you get acurrentTimeproperty for free :-) This property could be used to check against anextTimevariable like so:As I said, I don't know if this speeds things up, but it'll simplify your code, which is always good :-)