3

I'm programming a game in SpriteKit and am coding a section where the "level" is loaded in from a text file, placing a wall node in every spot marked by an "x" in the text file. However, if I know that there are going to be a lot of nodes, and they're all being loaded from the same "wall.png" file, is it more efficient to load the image once and then duplicate the object each time needed, or just load the image each time?

for line in lines {
  for letter in line {
    if letter == "x" {
      let wall = SKSpriteNode(imageNamed: "wall")
      self.addChild(wall)
    } else { ... }
  }
}

VS

let wall = SKSpriteNode(imageNamed: "wall")
for line in lines {
  for letter in line {
    if letter == "x" {
      self.addChild(wall.copy())
    } else { ... }
  }
}

self in this scope is a class holding the level that extends SKNode, so I'm adding walls to self and then adding that SKNode to the scene.

jaxreiff
  • 503
  • 1
  • 4
  • 14
  • Try it both ways and count how many you can add before you get a low memory warning from iOS. – vacawama Jul 06 '16 at 01:36
  • I was thinking more in terms of how quickly they can be loaded, I'd assume that both would have similar memory usage once loaded? – jaxreiff Jul 06 '16 at 02:15
  • I think is more or less the same, the complexity of the code is 2^n drived by two for cycle, the line self.addChild(wall.copy()) or let wall = SKSpriteNode(imageNamed: "wall") maybe doesn't add more time. You can try to add delta time at the start and finish of for cycle and check. – Simone Pistecchia Jul 06 '16 at 08:25

2 Answers2

1

To answer your question without resorting to 3rd party support

Go with the 2nd option (the copy option)

This will use the same texture across multiple sprites, where as the 1st choice creates a new texture every iteration.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • Thank you! If I made one texture, and used that texture in the initializer of a bunch of SKSpriteNodes, would the texture be referenced or copied? – jaxreiff Jul 06 '16 at 21:20
  • Referenced, if you used texture atlases. It will also be referenced everywhere – Knight0fDragon Jul 07 '16 at 11:36
0

The approach to developing your project remember me a TileMap. Pay attention because you can earn a lot of time instead to load each elements, you can prepare your levels and you have more fun.

There are thousand of tutorials that can help you to build a TileMap with Sprite-kit and Swift. Many of them use this GitHub library called also JSTileMap here

In these tutorials you can learn to how to:

  • Create a map with Tiled
  • Add the map to the game
  • Scroll the map to follow the player

  • Use object layers.

It's very simple , for example you can load a tmx map:

let tiledMap = JSTileMap("mapFileName.tmx") //map name
if t = tileMap {
    self.addChild(tiledMap)
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133