Search code examples
c#matrixxna

XNA View Matrix Issues


I've been working on something that loads the geometry of a game and follows the players position and view but I've ran into a problem: I can't rotate the view without all the axis being messed up.

Here's a screenshot of the program with a pitch and yaw of 0 (just like the game's client): https://i.sstatic.net/DXhIr.jpg

Here's my view matrix code:

public void UpdateViewMatrix()
{
        Vector3 pos = Position;
        pos.X *= -1;
        pos.Y *= -1;
        pos.Z *= -1;

        this.ViewMatrix = Matrix.CreateScale(1) * Matrix.CreateLookAt(Vector3.Zero, new Vector3(1, 0, 0), new Vector3(0, 0, 1)) * Matrix.CreateTranslation(pos) * Matrix.CreateFromYawPitchRoll(-MathHelper.PiOver2, -MathHelper.PiOver2, MathHelper.Pi);

        this.Frustum.Matrix = (this.ViewMatrix * this.ProjectionMatrix);
        if (this.CameraUpdated != null) this.CameraUpdated(this, new EventArgs());
}

I'm unsure why I have to flip all the coordinates as well before I update the view matrix.

Thanks in advance!


Solution

  • I'm unsure why I have to flip all the coordinates as well before I update the view matrix

    You probably don't.

    In an Xna first person shooter, an easy way to handle the camera's view matrix to follow a character is to create a copy of that character's world matrix, offset it behind and slightly above, then invert it. That way, all the rotation and position manipulation that is done for the player does not have to be duplicated for the camera. This is a simple example of this:

    //player moved and rotated and player's world matrix is determined
    
    Matrix cameraWorld = playerWorld;
    cameraWorld.Translation += (cameraWorld.Backward * followingDistance) +
                               (cameraWorld.Up * verticalOffset);
    ViewMatrix = Matrix.Invert(cameraWorld);
    

    Now the camera view matrix is orientated identically as the player and will stick to him like glue.