XNA中的FPS样式相机目标计算

时间:2013-04-01 15:21:36

标签: c# windows-phone-7 math xna 3dcamera

我需要的是根据相机位置,Y旋转和Z旋转来计算我的外观3d矢量的位置,我认为任何大于0的数字都足以让相机看到相机的距离

这是我用来控制相机并计算视图和投影矩阵等的静态类。

涉及职位和轮换的班级成员:

public static Vector3 Position { get; set; } //Publicly available for use outside the class
public static Vector3 Rotation { get; set; }
private static Vector3 camPos = new Vector3(0.0f, 200.0f, 300.0f); //However we work with these for manipulation of values
private static Vector3 camTarget = new Vector3(0, 0, -1200.0f);

private static float rotY = 0, rotZ = 0; //I believe that these are the correct axis following the right hand catasian coordinate system

我相机的更新功能:

public static void Update()        
{
    //Controls here

    //Update Position here
    Position = camPos;            

    //Update camTarget based on Position, rotY and rotZ <- Need help with this bit

    //After calculating camTarget update Rotation
    Rotation = camTarget;

    UpdateMatrices();
}

UpdateMatrices()处理其他所有内容并按原样运行,但这里只是为了以防万一你希望看到它:

public static void UpdateMatrices()
{
    Matrix rotationMatrix = Matrix.CreateRotationX(MathHelper.ToRadians(90));
    Vector3 transformedReference = Vector3.Transform(Vector3.Forward, rotationMatrix);

    View = Matrix.CreateLookAt(Position, Rotation, Vector3.Forward);
    Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
    World = Matrix.Identity;

    CamBoundingFrustrum = new BoundingFrustum(View * Projection);
}

有人愿意和我分享这个秘密吗?

1 个答案:

答案 0 :(得分:3)

不是使用Vector3.Forward,而是从旋转矩阵中提取.Forward.Up向量:

    public void UpdateMatrices()
    {
        /// assumes Rotation is a Vector3 containing rotation around each axis expressed in radians
        Matrix rotationMatrix = Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z);
        /// View = Matrix.CreateLookAt(Position, Rotation, Vector3.Forward);

        View = Matrix.CreateLookAt(Position, Position + rotationMatrix.Forward, rotationMatrix.Up);
        Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);

        /// World matrix needs to match your translation and rotation used above
        /// XNA expects matrices to be concatenated in SRT (scale, rotation, then translate) order:
        World = rotationMatrix * Matrix.CreateTranslation(Position);

        CamBoundingFrustrum = new BoundingFrustum(View * Projection);
    }

请注意,您必须将相机的翻译(通过您正在存储的矢量或相机的世界矩阵.Translation属性)添加到RotationMatrix.Forward以获得真实目标。

矩阵.Forward.Backward.Left.Right.Up.Down属性与等效{{1}相同由旋转矩阵转换的属性。所以,Vector3指向你正在寻找的方向,RotationMatrix.Forward与之正交,等等。

如果您只使用.Up,则不会获得转换后的矢量,并且可能会发生奇怪的事情。

其他说明:

  1. 不要让一切都静止。在Vector3.Forward期间创建相机类的实例,并将其添加为属性。 Game.Initialize()应谨慎使用 - 它可能会导致各种有趣的线程问题,这些问题会让您感到精神错乱。
  2. 我还建议切换到四元数而不是偏航/滚动/俯仰(如果你还没有),因为它避免了灵活锁定,但这是一个不同的主题。