我正在为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轴,并将相机的间距更改为从birdeye视图到地面视图。我遇到的麻烦就是让相机旋转起作用。
当旋转值改变时,它只有在音高改变时才有效 - 从程序启动时的默认值开始(直接向下看'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);
此外,还有一个q& a,我发现它可以帮我编写代码XNA Rotate Camera Around It's CreateLookAt "Target"
答案 0 :(得分:1)
应在不改变其长度的情况下旋转偏移,然后将其添加到摄像机位置。
我认为应该是这样的:
offset = new Vector3(0, 0, 10);
Vector3 rotatedOffset = Vector3.Transform( offset,
Matrix.CreateRotationX(cameraPitch)
* Matrix.CreateRotationZ(cameraRotation));
cameraPosition = cameraLookAt + rotatedOffset;