我正在为 3D 游戏创建相机。相机由以下变量组成:
static Vector3 cameraLookAt = new Vector3(0, 0, 0);
static Vector3 cameraPosition;
static float cameraZoom = 25; // Field of view
const int cameraZoomNear = 3; // The furthest the camera can zoom in
const int cameraZoomFar = 45; // The furthest the camera can zoom out
static float cameraPitch; // Amount to change the pitch
static float cameraRotation; // Amount to change the rotation
默认情况下,“cameraLookAt”位于 (0, 0, 0),“cameraPosition”位于 (0, 0, 10),这意味着相机位于“cameraLookAt”位置的正上方,可以鸟瞰下方的对象(红绿蓝xyz平面测试对象)
'cameraLookAt' 可以沿 x 和 y 轴移动,然后相对于 'cameraLookAt' 位置和 'cameraPitch' 和 'cameraRotation' 的当前值计算 'cameraPosition'
目前,您可以很好地围绕 x/y 轴移动并更改相机的俯仰角以从鸟瞰视图变为地面视图。我遇到的问题是让相机旋转工作。
当旋转值改变时,它只有在音高改变时才会有任何影响 - 从程序启动时的默认值开始(直接向下看'cameraLookAt')
当值发生变化时,您可以围绕 Z 轴旋转,但视图也会滚动,因此当您旋转 180 度时,相机也已滚动 180 度,并且您的视图是颠倒的。
下面是确定“cameraPosition”所在位置的代码,我确定这些行中的修复行。
cameraPosition = cameraLookAt + new Vector3(0, 0, 10);
Vector3 temp = Vector3.Normalize(cameraPosition - cameraLookAt); //creates a unit length vector that points in the direction from 'lookAt' to 'position'
cameraPosition = Vector3.Transform(cameraPosition - cameraLookAt, Matrix.CreateRotationX(cameraPitch)) + cameraLookAt;
cameraPosition = Vector3.Transform(cameraPosition - cameraLookAt, Matrix.CreateRotationZ(cameraRotation)) + cameraLookAt;
view = Matrix.CreateLookAt(cameraPosition, cameraLookAt, new Vector3(0.0f, 1.0f, 0.0f));
projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(cameraZoom), graphics.GraphicsDevice.Viewport.AspectRatio, nearClip, farClip);
这里还有一个问答,我发现它可以帮助我首先对其进行编码XNA Rotate Camera Around It's CreateLookAt "Target"