1

I have a few square-shaped nodes (like floor tiles) going along the screen and I'd like to restrict my player (P) node to moving within these nodes.

---------------------------------
|   | P |   |   |   |   |   |   |    <- Want no movement allowed 
---------------------------------       outside of these squares.
            |   |
        -------------
        |   |   |   | ...  
        -------------

I'm wondering if there's an elegant way to do this with SpriteKit Physics, that doesn't involve putting invisible blocks all the way around the floor.

Thanks!

iank
  • 800
  • 3
  • 10
  • 32

2 Answers2

3

An SKConstraint object describes a mathematical constraint on a node’s position or orientation.

You can use SKConstraint to keep a node a certain distance from a specific point in horizontal axis:

let center = size.width/2.0, difference = CGFloat(170.0)
let leftConstraint = SKConstraint.positionX(SKRange(constantValue: center - difference))
let rightConstraint = SKConstraint.positionX(SKRange(constantValue: center + difference))    
player.constraints = [leftConstraint, rightConstraint]

You can also decide to enable or disable a certain constraint during the game:

leftConstraint.enabled = false
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
1

You use edge based physics bodies, not volume based physics bodies. So in your construction of the physics body, look for anything with edge in the constructor. Now, if you want to be able to walk between the tiles, you will have to create 1 physics body for the outer wall of your floor, because doing it tile by tile will mean you will be stuck in individual tiles.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44