Time for action – repositioning the camera
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
In the
Update()
method of the Player class, add a call to reposition the camera right before the call tobase.Update()
:repositionCamera();
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...