A. Tohamy A. Tohamy - 1 year ago 77
Swift Question

How do I wrap x & y axis in SpriteKit?

So in my GameScene I have these lines in the beginning of func didMoveToView

let border = SKPhysicsBody(edgeLoopFromRect: self.frame)
border.friction = 0
self.physicsBody = border
self.physicsWorld.contactDelegate = self

It works fine for preventing my player from going outside the screen; However, I want my player, or anything else in the scene, to go to the other side of the screen when touching the border. In other words: If i kept going right i would keep going right until i hit the border then my player would appear from the left border and continue going right in an endless loop.

Same goes for y axis.

How is this possible in code?

Answer Source

Try this code:

if player.position.x + player.size.width / 2 > size.width {
    player.position.x = -player.size.width 
else if player.position.x + player.size.width / 2 < 0 {
    player.position.x = size.width + player.size.width / 2

Same logic for Y axis.