沿相机所面对的方向移动相机

本文关键字:相机 方向 移动 面对 | 更新日期: 2023-09-27 17:57:36

我在微软网站上学习了如何在XNA中使第一人称相机在3D世界中旋转和移动的教程。但是,当我沿着相机的Y轴旋转相机时,它不会移动它旋转/面对的方向,而是像面对最初面对的方向一样移动。

这是我的代码:

static Vector3 avatarPosition = new Vector3(0, 0, 0);
static Vector3 cameraPosition = avatarPosition;
Vector3 cameraReference = new Vector3(10, 0, 0);
// Create a vector pointing the direction the camera is facing.
Matrix world = Matrix.CreateWorld(new Vector3(0, -1, 0), Vector3.Forward, Vector3.Up);
Matrix rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(0));
int Rot = 0;
Vector3 worldVector = new Vector3(5,-2, 0);
Matrix view, proj;
Vector3 cameraLookat;
Update()
{
    world = Matrix.CreateWorld(worldVector, Vector3.Forward, Vector3.Up);
    if (IsKeyDown(Keys.W))
        avatarPosition += new Vector3(0.2f, 0f, 0);
    if (IsKeyDown(Keys.S))
        avatarPosition += new Vector3(-0.2f, 0f, 0);
    if (IsKeyDown(Keys.A))
        avatarPosition += new Vector3(0f, 0f, -0.2f);
    if (IsKeyDown(Keys.D))
        avatarPosition += new Vector3(0f, 0f, 0.2f);
    if (IsKeyDown(Keys.Left))
        Rot += 1;
    if (IsKeyDown(Keys.Right))
        Rot += -1;
    rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(Rot));
    // Create a vector pointing the direction the camera is facing.
    Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix);
    // Calculate the position the camera is looking at.
    cameraLookat = transformedReference + cameraPosition;
    // Set up the view matrix and projection matrix.
    view = Matrix.CreateLookAt(cameraPosition, cameraLookat, new Vector3(0.0f, 1.0f, 0.0f));
    proj = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), graphics.GraphicsDevice.Viewport.AspectRatio,
                                          0.1f, 1000);
    cameraPosition = avatarPosition;
 }

有人能告诉我为什么相机没有按旋转的方式移动吗?或者有人能给我一个该死的代码吗?

沿相机所面对的方向移动相机

我认为您遇到的问题来自代码的这个区域:

if (IsKeyDown(Keys.W))
    avatarPosition += new Vector3(0.2f, 0f, 0);
if (IsKeyDown(Keys.S))
    avatarPosition += new Vector3(-0.2f, 0f, 0);
if (IsKeyDown(Keys.A))
    avatarPosition += new Vector3(0f, 0f, -0.2f);
if (IsKeyDown(Keys.D))
    avatarPosition += new Vector3(0f, 0f, 0.2f);

与其直接沿着x或z轴平移avatarPosition,不如使用您所指向的方向,该方向似乎是您的transformedReference变量。

例如,向前移动相机所面对的方向:

if (IsKeyDown(Keys.W))
    avatarPosition += transformedReference;

但是,由于transformedReference变量看起来是标准化的,它可能不会将化身移动到您希望的距离。在这种情况下,只需将其乘以某个常数MOVEMENT_SPEED,就可以得到这样的东西:

if (IsKeyDown(Keys.W))
    avatarPosition += transformedReference * MOVEMENT_SPEED;