Define map bounds and center on player node?

前端 未结 2 1004
花落未央
花落未央 2021-01-07 03:57

I\'m working on a sidescroller with Spritekit and Swift. I don\'t understand how to define a playable area bigger than the screen and center the camera on the player. How ca

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-07 04:40

    I followed Ray Wenderlich's tutorial on a side scrolling game Super Koalio (or something like that). That game is a side scroller where the game map is larger sideways than the screen. The following code is for my game which is a vertical scrolling game.

    In the update method I call a method called setViewPointCenter.

    -(void)update:(CFTimeInterval)currentTime
      {
        // Other things are called too
        [self setViewPointCenter:self.player.position];
      }
    

    Then in that method you just update the view

    - (void)setViewPointCenter:(CGPoint)position
    {
      NSInteger x = MAX(position.x, self.size.width / 2);
      NSInteger y = MAX(position.y, self.size.height /2);
      x = MIN(x, (self.map.mapSize.width * self.map.tileSize.width) - self.size.width / 2);
      y = MIN(y, (self.map.mapSize.height * self.map.tileSize.height) - self.size.height / 2);
      CGPoint actualPostion = CGPointMake(x, y);
      CGPoint centerOfView = CGPointMake(self.size.width/2, self.size.height/2);
      CGPoint viewPoint = CGPointSubtract(centerOfView, actualPostion);
      self.map.position = viewPoint;
    }
    

    Now my character is always in the center of the screen. I did change some items from horizontal to vertical, but at least you get an idea. Also, I used a tile map that is why you see mapSize and tileSize. You might want to take a look at Ray's tutorial. And of course you will need to convert into the methods into Swift!!

提交回复
热议问题