I'm writing a 2D game engine. I need to add a camera to my world that can zoom in and out as well as move away from its initial position at (0,0)
at the center of the world.
The main issue can be seen in this video. When the camera hasn't yet moved (still at 0,0
), I can click anywhere in the visible world and the click is mapped to the correct world position. I can even zoom and everything including the mouse position is scaled correctly. However, the moment I move the camera, the position becomes offset by a percentage of the camera movement. (This is clearer in the video.)
I have tried calculating the draw position and world mouse position in many different ways, but I always get the same issue.
What might be wrong?
Here's the code for both object position to screen position and mouse position to world position conversion:
public Vector2 GetDrawCoord(Vector2 position)
{
return new Vector2(((position.X - cameraCenter.X)) * zoom + graphics.Viewport.Width / 2,
graphics.Viewport.Height - ((position.Y - cameraCenter.Y) * zoom + graphics.Viewport.Height / 2));
}
public Vector2 GetClickCoord(Vector2 position)
{
return new Vector2((position.X - graphics.Viewport.Width / 2 + cameraCenter.X) / zoom,
(graphics.Viewport.Height / 2 - position.Y + cameraCenter.Y) / zoom);
}
Update:
New code:
Vector3 vec = graphics.Viewport.Unproject(new Vector3(position.X, position.Y, 0f),
Matrix.CreateOrthographic((float)graphics.Viewport.Width, (float)graphics.Viewport.Height, 0f, 0f),
cameraMatrix,
Matrix.Identity);