XNA 4.0: 2D Camera Y and X are going in wrong direction

Posted by Setheron on Game Development See other posts from Game Development or by Setheron
Published on 2011-08-19T13:33:22Z Indexed on 2012/12/16 5:20 UTC
Read the original article Hit count: 149

Filed under:
|
|
|
|

I asked this question on stackoverflow but assumed this might be a better area to ask it as well for a more informed answer.

My problem is that I am trying to create a camera class and have it so that my camera follows the proper RHS, however the Y axis seems to be inverted since on the screen the 0 starts at the top.

Here is my Camera2D Class:

    class Camera2D
    {
        private Vector2 _position;
        private float _zoom;
        private float _rotation;
        private float _cameraSpeed;
        private Viewport _viewport;
        private Matrix _viewMatrix;
        private Matrix _viewMatrixIverse;

        public static float MinZoom = float.Epsilon;
        public static float MaxZoom = float.MaxValue;

        public Camera2D(Viewport viewport)
        {
            _viewMatrix = Matrix.Identity;
            _viewport = viewport;
            _cameraSpeed = 4.0f;
            _zoom = 1.0f;
            _rotation = 0.0f;
            _position = Vector2.Zero;
        }

        public void Move(Vector2 amount)
        {
            _position += amount;
        }

        public void Zoom(float amount)
        {
            _zoom += amount;
            _zoom = MathHelper.Clamp(_zoom, MaxZoom, MinZoom);
            UpdateViewTransform();
        }

        public Vector2 Position
        {
            get { return _position; }
            set { _position = value; UpdateViewTransform(); }
        }

        public Matrix ViewMatrix
        {
            get { return _viewMatrix; }
        }


        private void UpdateViewTransform()
        {
             Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0)) * 
                           Matrix.CreateScale(new Vector3(1f, 1f, 1f));

             _viewMatrix = Matrix.CreateRotationZ(_rotation) *
                          Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) *
                          Matrix.CreateTranslation(_position.X, _position.Y, 0.0f);

             _viewMatrix = proj * _viewMatrix;

        }



    }

I test it using SpriteBatch in the following way:

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    Vector2 position = new Vector2(0, 0);
    // TODO: Add your drawing code here
    spriteBatch.Begin(SpriteSortMode.Immediate,
        BlendState.AlphaBlend,
        null,
        null,
        null,
        null,
        camera.ViewMatrix);

    Texture2D circle = CreateCircle(100);
    spriteBatch.Draw(circle, position, Color.Red);
    spriteBatch.End();

    base.Draw(gameTime);
}

© Game Development or respective owner

Related posts about XNA

Related posts about c#