Frage

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]]];

}
War es hilfreich?

Lösung

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.

Andere Tipps

In your SKScene:

self.physicsBody=[SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsWorld.gravity=CGVectorMake=(0,0);
_player.physicsBody=[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(10,10)];//example; use bodyWithPolygonFromPath:yourCGPath if player has more complex form, or bodyWithCircleOfRadius:radius if its shape is circle
_player.physicsBody.velocity=CGVectorMake(10,10); //or more then 10,10

Good luck!

just add the bottom code to your method that is called it should stop all physical bodies from leaving the screen!! veryuseful!

     SKPhysicsBody* gameborderBody = [SKPhysicsBody        bodyWithEdgeLoopFromRect:self.frame];
      // 2 Set physicsBody of scene to borderBody
      self.physicsBody = gameborderBody;
      // 3 Set the friction of that physicsBody to 0
      self.physicsBody.friction = 1.0f;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top