Pec*_*tum -1 c# xna camera xna-4.0 monogame
I am trying to make a scrolling level to a test game I am doing as a learning exercise. I have created a map containing lots of tiles which are drawn according to their position in an array. I basically want the camera to scroll down the level, but at the moment it just frantically shakes up and down a little bit.
I have a camera class which is just a blank static class containing a static vector2 for the camera location. It is just set as 50, 50 as all the tiles are 50 by 50.
Then in my maps update method I have the following:
public void Update(GameTime gameTime) {
Camera.Location.Y = MathHelper.Clamp(Camera.Location.Y + (float)speed, 0, (300 - 18) * 50)
}
Run Code Online (Sandbox Code Playgroud)
The 300 and 18 are the total number of tiles and the number of tiles on screen (vertically).
I am completely lost so would appreciate any help or advice.
这是我在游戏中使用的一个简单的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
这个想法是当你像这样绘制你的精灵批次时,将它作为一个变换应用:
var screenScale = GetScreenScale();
var viewMatrix = Camera.GetTransform();
_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
null, null, null, null, viewMatrix * Matrix.CreateScale(screenScale));
Run Code Online (Sandbox Code Playgroud)
您可能还注意到屏幕比例尺的使用。虽然与相机没有直接关系,但它是一种确保您的屏幕缩放到所需分辨率的方法。通过这种方式,您可以独立于分辨率绘制场景并在最后对其进行缩放。以下是屏幕缩放方法供参考:
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);
}
Run Code Online (Sandbox Code Playgroud)