Time for action - repositioning the camera

  1. Add the Helper Methods region and the repositionCamera() method to the Player class:
    #region Helper Methods
    private void repositionCamera()
    {
    int screenLocX = (int)Camera.WorldToScreen(worldLocation).X;
    if (screenLocX > 500)
    {
    Camera.Move(new Vector2(screenLocX - 500, 0));
    }
    if (screenLocX < 200)
    {
    Camera.Move(new Vector2(screenLocX - 200, 0));
    }
    }
    #endregion
    
  2. In the Update() method of the Player class, add a call to reposition the camera right before the call to base.Update():
    repositionCamera();
    
  3. Execute the Gemstone Hunter application and move towards the right side of the screen.

What just happened?

During each update frame, the current screen position of the character is checked. If the character has gotten too close to the edge of the screen (200 pixels from the left edge, or 300 pixels from the right edge), the camera's position is adjusted to keep the character within those bounds.

If the camera is already as far in either direction as it can go, nothing will happen this behavior is built into the Camera class. This allows the character to move to the edge of the map instead of requiring us to impose some kind of artificial barrier in the game world.

At the moment, however, we are still running around on a huge empty expanse. It may be a bit difficult to recognize that the camera is in fact scrolling when you get near the edge of the screen. To resolve that problem, we need to begin displaying our level map.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.193.232