Search code examples
iosobjective-csprite-kitgame-physics

Sprite Kit - Do not allow node to move out of screen


I am creating a game where I do not want the player to be able to move out of the screen. The node follows the players moving touch. The code I have "under construction" so the player can't move out on the top or right side, but I do not want the player to be able to move out on any of the sides.

- (void)movementPlayer {
    SKAction * actionMoveX =  [SKAction moveToX:MIN(location2.x - playerPositionX, self.size.width - (_player.size.width/2)) duration:0];

    SKAction * actionMoveY = [SKAction moveToY:MIN(location2.y - playerPositionY, self.size.height - (_player.size.height/2)) duration:0];

        [_player runAction:[SKAction sequence:@[actionMoveX, actionMoveY]]];

}

Solution

  • You should create a physics world and add a border rectangle around the screen. This border must have a physics body that is set to collide with the physics body collision category given to your player node. If the player node starts inside the border, the player cannot leave the screen and no additional coding is required (besides properly setting up collision categories for each physics body)

    RayWenderlich.com has easy to understand game tutorials that show how to handle collisions following the sprite kit manual.