这是我在游戏中使用的一个简单的 2D 相机类。
public class Camera2D
{
public Camera2D()
{
Zoom = 1;
Position = Vector2.Zero;
Rotation = 0;
Origin = Vector2.Zero;
Position = Vector2.Zero;
}
public float Zoom { get; set; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public Vector2 Origin { get; set; }
public void Move(Vector2 direction)
{
Position += direction;
}
public Matrix GetTransform()
{
var translationMatrix = Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0));
var rotationMatrix = Matrix.CreateRotationZ(Rotation);
var scaleMatrix = Matrix.CreateScale(new Vector3(Zoom, Zoom, 1));
var originMatrix = Matrix.CreateTranslation(new Vector3(Origin.X, Origin.Y, 0));
return translationMatrix * rotationMatrix * scaleMatrix * originMatrix;
}
}
这个想法是在您绘制精灵批次时将其应用为变换,如下所示:
var screenScale = GetScreenScale();
var viewMatrix = Camera.GetTransform();
_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
null, null, null, null, viewMatrix * Matrix.CreateScale(screenScale));
您可能还注意到屏幕比例的使用。虽然与相机没有直接关系,但它是一种确保您的屏幕缩放到所需分辨率的方法。通过这种方式,您可以绘制独立于分辨率的场景并在最后对其进行缩放。以下是屏幕缩放方法供参考:
public Vector3 GetScreenScale()
{
var scaleX = (float)_graphicsDevice.Viewport.Width / (float)_width;
var scaleY = (float)_graphicsDevice.Viewport.Height / (float)_height;
return new Vector3(scaleX, scaleY, 1.0f);
}