user1585121
user1585121

Reputation:

Best practice for spawning many time the same node in SpriteKit (swift)

In my game I spawn many enemies with random coordinates, but they share the same internal data.

Currently I have a function SpawnEnemy() who looks like this:

func spawnRedPawn(timer: NSTimer) {
    var redPawn = Ship(entityNamed: ESHIP_REDPAWN)
    let action = SKAction.moveToX(0, duration: timer.userInfo as! NSTimeInterval)
    let actionDone = SKAction.removeFromParent()

    redPawn.position = CGPoint(x: self.size.width, y: CGFloat(arc4random_uniform(UInt32(self.size.height - redPawn.size.height))))
    redPawn.setupPhysicsBody(PC.enemy)
    redPawn.setupContactTestBitmask([PC.projectile, PC.player])
    redPawn.addEmitter("propulsionParticle", offset: CGPointMake(redPawn.size.width / 2 + 5, 0))
    redPawn.runAction(SKAction.sequence([action, actionDone]))
    self.addChild(redPawn)
}

PS: the function format (called by NSTimer Selector()) will probably be changed

I am new to SpriteKit but I feel that this setup process is quite resource intensive right?

My question is: is it possible/would it be better to run this fonction only once, and then only duplicate the created enemy?

Upvotes: 1

Views: 857

Answers (1)

Whirlwind
Whirlwind

Reputation: 13665

Here are some basics that you should know:

What you can do (especially if you are experiencing performance problems) is to:

  • use texture atlases. This way you are reducing number of cpu draw calls required to render a sprites.

  • cache different resources like emitters (or sounds). This way you are keep them in memory and you don't need to read them from disk. Search Apple's Adventure game to see how you can cache the resources. Basically, you preload everything before gameplay using the completion handler.

One way you could go is to pre-create a bunch of nodes and use them until game is finished. This way you won't re-create the SKSpriteNodes many times (which sometimes can cause noticeable lag). Here you can read about that.

Important:

  • Don't take simulator results into account, because those are not realistic. If you are interested in real information about performance you should test on device.

Hope this helps a bit.

Upvotes: 3

Related Questions