Time for action – staying in bounds

  1. Create a region called "Movement Limitations" in the Player class:
    #region Movement Limitations
    #endregion
  2. Inside the Movement Limitations region, add the clampToWorld() method:
    private static void clampToWorld()
    {
        float currentX = BaseSprite.WorldLocation.X;
        float currentY = BaseSprite.WorldLocation.Y;
    
        currentX = MathHelper.Clamp(
            currentX, 
            0, 
            Camera.WorldRectangle.Right - BaseSprite.FrameWidth);
    
        currentY = MathHelper.Clamp(
            currentY,
            0,
            Camera.WorldRectangle.Bottom - BaseSprite.FrameHeight);
    
        BaseSprite.WorldLocation = new Vector2(currentX, currentY);
    }
  3. Add a declaration to the Player class to define the area in which the camera should attempt to keep the player:
    private static Rectangle scrollArea = new Rectangle(150, ...

Get XNA 4.0 Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.