0
\$\begingroup\$

My 2D camera follows the character fine without any zooming. However, when I tried adding a zoom feature using the Matrix.CreateScale(), the camera no longer follows the character properly.

public class Camera
{
    private Matrix transform;

    public Matrix Transform
    {
        get { return transform; }
        set { value = transform; }
    }

    public Viewport view;
    public  Vector2 center;
    float zoom;
    float rotation;
    public float Zoom{
        get{return zoom;}
        set { value = zoom; }
    }

    public Camera(Viewport newView)
    {
        view = newView;
        zoom = 2;
        rotation = 0;
    }

    public void Update(Vector2 position, int xOffset, int yOffset)
    {

        if (position.X < view.Width / 2)
            center.X = view.Width / 2;
        else if (position.X > xOffset - (view.Width / 2))
            center.X = xOffset - (view.Width / 2);
        else center.X = position.X;


        if (position.Y < view.Height / 2)
            center.Y = view.Height / 2;
        else if (position.Y > yOffset - (view.Height / 2))
            center.Y = yOffset - (view.Height / 2);
        else center.Y = position.Y;




        transform = Matrix.CreateTranslation(
            new Vector3(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0)) * 
            Matrix.CreateScale(Zoom, Zoom, 1.0f) * Matrix.CreateRotationZ(rotation) *
            Matrix.CreateTranslation(-center.X + (view.Width / 2), -center.Y + (view.Height / 2), 0); 





    }
}

The camera is updated with:

camera.Update(character.Position, map.Width, map.Height);

With the width and height of the tilemap and the characters current position. If I change the zoom factor how do i keep the player still in the center w/ the camera following?

\$\endgroup\$
  • 2
    \$\begingroup\$ You shouldn't create duplicate questions. (stackoverflow.com/questions/21203343/…). If you don't get an answer in one stackexchange site, you should delete it before asking the exact same thing on a different stackexchange site! \$\endgroup\$ – Joe Shanahan Jan 18 '14 at 20:52
  • \$\begingroup\$ @Joe I've asked the SO mods to merge that here if possible. \$\endgroup\$ – Anko Feb 20 '14 at 6:45
2
\$\begingroup\$

From just a quick glance it looks like your matrix is incorrect. ISROT (identity, scale, rotate, orbit, translation) is the order you should apply your operations. Your applying translation twice for some reason.

transform =
    Matrix.CreateScale(Zoom, Zoom, 1.0f)
    * Matrix.CreateRotationZ(rotation)
    * Matrix.CreateTranslation(-center.X + (view.Width / 2),
                               -center.Y + (view.Height / 2),
                               0); 
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.