Search code examples
iosswiftsprite-kitsksceneskcameranode

Swift: Wrap / loop / repeat nodes outside camera bounds?


I'm making a game with a camera setup that could be compared to the one in Agar.io. It can go up, down, left and right. However, in Agar.io you're limited to the space of the map. If you run into a side of the map then you have to go back.

However, in my game I want the camera to 'wrap' to the opposite side of the map.

I couldn't find any examples so I made my own:

// This is in an SKScene

private func wrapNodes() {

  let camPos = camera!.position // SKCameraNode of current scene

  for node in self.children {

    let nodePos = node.position

    let x = camPos.x - nodePos.x
    if x > spawnRect.width * 0.5 {
      node.position.x = nodePos.x + spawnRect.width // spawnRect = map size
    } else if x < -spawnRect.width * 0.5 {
      node.position.x = nodePos.x - spawnRect.width // spawnRect = map size
    }

    let y = camPos.y - nodePos.y
    if y > spawnRect.height * 0.5 {
      node.position.y = nodePos.y + spawnRect.height // spawnRect = map size
    } else if y < -spawnRect.height * 0.5 {
      node.position.y = nodePos.y - spawnRect.height // spawnRect = map size
    }
  }
}

Surprisingly due to my terrible math skills, this actually seems to work.

However, there are two problems with this.

The first is that I don't trust myself at all, and I feel like I must've made a mistake somewhere.

The second is that it takes quite a long time to loop through all the nodes in the scene, so I was hoping there would be a faster way, but I can't find one. So, I was wondering if anyone knew a quicker way to do this.

Any ideas would be appreciated!


Solution

  • I can't think of any way this could be faster or better at the moment, so I think I'll leave this post here in case someone needs it in the future