[英]I can't fix camera to any object in a 2D Matrix
问题描述:我正在尝试使用XNA框架在C#中开发一些具有地形冲突的2D游戏。 我已经完成了简单的地形生成,并且物体(例如汽车)可以在此地形上移动。 但是现在,我遇到了该车的摄像头修复问题。 我尝试在网络上进行大量搜索,但找不到适合我的解决方案。 当我运行程序时,它崩溃了。
我尝试了什么? 我试图在调试模式下运行该程序,并且始终在Camera构造函数中始终停留在NullReferenceException
上。
一段Camera.cs
public class Camera {
public Matrix transform;
private Viewport view;
private Vector2 centering;
public Camera(GraphicsDevice view)
{
this.view = view.Viewport;
}
public void Update(GameTime gameTime, TheGame theGame)
{
centering = new Vector2(theGame.movement.position.X + theGame.movement.position.Y / 2);
transform = Matrix.CreateScale(new Vector3(1, 1, 0)) *
Matrix.CreateTranslation(new Vector3(-centering.X, -centering.Y, 0));
}
}
相机实例调用:
private Camera camera;
public TheGame(Game game)
:base(game)
{
this.game = game;
camera = new Camera(GraphicsDevice); //<---- here is the crash
}
private Game game;
我的问题是:如何将相机固定在矩阵中的任何对象上,或者这样做的标准方法是什么,因为我认为知识非常重要。
之所以收到NullReferenceException
是因为GraphicsDevice
尚未初始化 。
不用在TheGame
构造函数中创建Camera
,而是在Initialize
方法中创建它:
protected override void Initialize()
{
base.Initialize();
camera = new Camera(GraphicsDevice);
}
如何将相机固定在矩阵中的任何对象上,或者这样做的标准方法是什么,因为我认为知识非常重要。
我假设您正在处理屏幕空间坐标,其中X从左到右增长,Y从上到下增长。 我还假设摄影机位置指示摄影机视图的左上角,并且摄影机位于本地空间中的{0,0}。
基于这些假设,并知道您要使相机居中放置的实体的位置,我们可以按以下方式计算相机平移变换:
transform = Matrix.CreateTranslation(new Vector3(
theGame.movement.position.X - view.Width / 2f,
theGame.movement.position.Y - view.Height / 2f,
0));
该变换表示:“ 将摄像机的左上角放在游戏对象上,并减去摄像机视口的一半以将其居中 ”。
请注意,您可能还希望将摄影机的坐标限制在0和游戏世界大小之间,以确保使用MathHelper.Clamp
不会使摄影机超出游戏世界的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.