1

再会。我正在开发一个 fps 游戏,但我的相机有问题,或者移动价格昂贵......因为它在执行移动时不会考虑相机位置......我试图用几种不同的方式修复它方式,但我想我只是不明白所需的数学:(

无论如何,这是代码:

    static public void UpdateCharacterPositionAndCamera(float time)
    {
        //mouse look update
        float rotationSpeed = 3f;
        if (Input.mouseState != Input.mouseStatePrevious)
        {
            float xDifference = Input.mouseState.X - Display.gd.Viewport.Width / 2;
            float yDifference = Input.mouseState.Y - Display.gd.Viewport.Height / 2;
            yRotation -= rotationSpeed * xDifference * time;
            xRotation -= rotationSpeed * yDifference * time;
            Mouse.SetPosition(Display.gd.Viewport.Width / 2, Display.gd.Viewport.Height / 2);
        }

        //camera
        Vector3 cameraPosition = playerPos;
        Vector3 cameraReference = new Vector3(0f, 0f, -1f);
        Matrix rotationMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(yRotation)) * Matrix.CreateRotationX(MathHelper.ToRadians(xRotation));
        Vector3 transformedReference = Vector3.Transform(cameraReference, rotationMatrix);
        Vector3 cameraLookat = cameraPosition + transformedReference;
        viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraLookat, new Vector3(0.0f, 1.0f, 0.0f));
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Display.gd.Viewport.AspectRatio, 0.1f, 2500.0f);

        //movement
        float moveSpeed = 5.0f;
        Vector3 moveVector = new Vector3(0, 0, 0);
        if (Input.keyState.IsKeyDown(Keys.Up) || Input.keyState.IsKeyDown(Keys.W))
            moveVector += new Vector3(0, 0, -1);
        if (Input.keyState.IsKeyDown(Keys.Down) || Input.keyState.IsKeyDown(Keys.S))
            moveVector += new Vector3(0, 0, 1);
        if (Input.keyState.IsKeyDown(Keys.Right) || Input.keyState.IsKeyDown(Keys.D))
            moveVector += new Vector3(1, 0, 0);
        if (Input.keyState.IsKeyDown(Keys.Left) || Input.keyState.IsKeyDown(Keys.A))
            moveVector += new Vector3(-1, 0, 0);
        if (Input.keyState.IsKeyDown(Keys.Q))
            moveVector += new Vector3(0, 1, 0);
        if (Input.keyState.IsKeyDown(Keys.Z))
            moveVector += new Vector3(0, -1, 0);
        playerPos += moveVector * moveSpeed;
    }

您能告诉我如何更改移动矢量,以便将相机方向考虑在内...?

4

2 回答 2

1

将移动向量乘以相机旋转矩阵,或其逆矩阵(我认为是逆矩阵)。它与视图矩阵相同,但没有平移。如果要将相机固定在平面上,则需要在之后将相应的组件归零,并可能对新向量进行归一化。我不熟悉 XNA API,所以我不能确切地告诉你使用哪些方法。您可能能够从视图矩阵中提取旋转矩阵,或者您可能需要查看与原点的差异(lookAt-positios)。

于 2012-09-15T15:40:58.453 回答
0

aere是我通常的做法:

   //movement 
    Matrix camWorld = Matrix.Invert(view);

    Vector3 moveVector = Vector3.Zero;
    ...
    if(...keys.Up... or ...keys.W...)
       moveVector += camWorld.Forward;
    if(... keys.right  or ... keys.D...)
       moveVector += camWorld.Right;
    ...
    moveVector.Normalize();
    PlayerPos += moveVector * moveSpeed;
于 2012-09-15T16:11:30.787 回答