Camera not moving correctly

by Labrockstar   Last Updated April 01, 2018 14:13 PM

I am currently working on a game in XNA and MonoGame. This game is supposed to be a port of KidsCanCode's tutorial series of creating tile-based games in Python. Here is a link to one of the videos in the series I'm talking about:

My issue is that my player and camera don't move like how KidsCanCode's player and camera move (you can see KidsCanCode's player and camera movement by clicking on the link above). My camera and player are out of sync. The player can easily go outside of the camera.

Here is the camera code:

public class Camera
    public float Rotation { get; private set; } = 0;
    //private Matrix OldTransform;
    //public Vector2 Position { get; private set; }
    public float Zoom { get; private set; } = 1f;

    public int ScreenWidth { get; set; }
    public int ScreenHeight { get; set; }

    public int MapWidth { get; set; }
    public int MapHeight { get; set; }

    private Vector2 Position;

    const float Velocity = 280f;

    public void GetTransformation(out Matrix transform)
        float x = -Position.X;
        float y = -Position.Y;

        transform =
      Matrix.CreateTranslation(new Vector3(x, y, 0));


    public Camera(int screenWidth, int screenHeight, int mapWidth, int mapHeight)
        ScreenWidth = screenWidth;
        ScreenHeight = screenHeight;

        MapWidth = mapWidth;
        MapHeight = mapHeight;

    public void ApplyPositionFromSprite(Sprite sprite)
        //Camera is supposed to center on sprite

        //Camera is always supposed to be ahead of player unless player is close to the edge

        float x = sprite.Position.X;
        float y = sprite.Position.Y;

        x = Math.Max(x, 0);
        y = Math.Max(y, 0);

        x = Math.Min(x, MapWidth - ScreenWidth);
        y = Math.Min(y, MapHeight - ScreenHeight);

        this.Position = new Vector2(x, y);


Can someone tell me what's wrong with my code? Here is a link to the GitHub page.

Answers 1

I found the answer to my problem was that I didn't apply the matrix transform of the camera to my player sprite. It works as it should now.

Also, as a side note, if you're rendering the sprite with an overload of SpriteBatch.Draw that accepts a Rectangle instead of a Vector2, then you should use an overload that accepts a Vector2 because of jittering that may occur due to rounding a float to an int.

April 01, 2018 19:03 PM

Related Questions

Monogame - custom json content importer

Updated June 07, 2016 08:07 AM

Best practice for scrollable viewport rendering

Updated June 27, 2015 20:05 PM

Monogame tilemap and camera render issue

Updated April 07, 2016 08:05 AM

only one tile being drawn xna c#

Updated September 27, 2016 09:05 AM