I have this class, I use it to draw sprites in my 2D game:
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace Namespace { /// <summary> /// Found this brilliant code at. /// http://adambruenderman.wordpress.com/2011/04/05/create-a-2d-camera-in-xna-gs-4-0/ /// </summary> public class CCamera2d { private const float zoomUpperLimit = 1.3f; private const float zoomLowerLimit = .85f; private float _zoom; private Matrix _transform; private Vector2 _pos; private float _rotation; private int _viewportWidth; private int _viewportHeight; private int _worldWidth; private int _worldHeight; public CCamera2d(Viewport viewport, int worldWidth, int worldHeight, float initialZoom = zoomLowerLimit) { _zoom = initialZoom; _rotation = 0.0f; _pos = Vector2.Zero; _viewportWidth = viewport.Width; _viewportHeight = viewport.Height; _worldWidth = worldWidth; _worldHeight = worldHeight; }
Now I canβt understand how not to create the position of the screen (mouse) on the world position. It would be great to have a function like this:
Vector2 ScreenToWorld(Vector2 onScreen, Matrix CameraTransformation)
For WorldToScreen I use the function (works fine):
public Vector2 WorldToScreen(Vector2 inWorld) { return Vector2.Transform(inWorld, Camera.CurrentTransformation); }
source share