2D Game Camera offest when following body

Topics: User Forum
Oct 7, 2013 at 2:35 AM
When moving the object around, the camera doesn't remain centered on the object.

I can't seem to locate the bug. Please help.
ConvertUnits.ToDisplayUnits(body.Position)-(Camera._screenCenter- Camera._cameraPosition)
Initial this returns zero.
After some movement it changes.


This is my Camera Class-
class Camera
        private static Matrix _view;
        public static Vector2 _cameraPosition;
        public static Vector2 _screenCenter;
        private static float _zoom;
        private static float _rotation;

        public static void Load(GraphicsDeviceManager _graphics)
            _view = Matrix.Identity;
            _cameraPosition = Vector2.Zero;
            _screenCenter = new Vector2(_graphics.GraphicsDevice.Viewport.Width / 2f, _graphics.GraphicsDevice.Viewport.Height / 2f);
            _rotation = 0f;
            _zoom = 1.0f;

        public static void HandleInput(KeyboardState state)
            if (state.IsKeyDown(Keys.Add) && _zoom < 1.0f)
                _zoom += 0.1f;
            if (state.IsKeyDown(Keys.Subtract) && _zoom > 0.1f)
                _zoom -= 0.1f;


        public static void Update()
            _view = Matrix.CreateTranslation(
                                        new Vector3(_cameraPosition - _screenCenter, 0f)) *
                                         Matrix.CreateRotationZ(_rotation) *
                                         Matrix.CreateScale(new Vector3(_zoom, _zoom, 1)) *
                                         Matrix.CreateTranslation(new Vector3(_screenCenter, 0f));

        public static void Follow(Body body)
            if (body != null)
                _cameraPosition = _screenCenter - ConvertUnits.ToDisplayUnits(body.Position);

        public static Matrix getView()
            return _view;
Oct 11, 2013 at 2:56 PM
It doesn't appear that you are ever updating the camera position. Try adding a call to Follow in your Update logic. Note, that you may want to add a Body target field to your Camera to allow it to know when it should be following a Body about the simulation.

Besides that, you should probably let the Game update loop handle calling update--I'm looking at the Update call at the end of HandleInput.

From the looks of things, it seems you are having issues following what your code is actually doing. I suggest some educational reading.