tags:

views:

43

answers:

2

I thought I understood matrix math well enough, but apparently I'm clueless

Here's the setup:

I have an object at [0,0,0] in world space. I have a camera class controlled by mouse movements to rotate and zoom around the object such that it always looks at it. Here is how I calculate my viewMatrix from the camera:

public Matrix viewMatrix { 
    get {
        return 
            Matrix.CreateFromAxisAngle(Vector3.Up, rotAngle)
                * Matrix.CreateFromAxisAngle(Vector3.Left, pitchAngle)
                * Matrix.CreateTranslation(0, 0, distance) 
        ;
    }
}

I need to be able to get the position of the camera in world space so I can get its distance from the box--particularly its distance from each face of the box. How can I get the camera's xyz position in world space coords?

I've tried:

// all of these only return [0, 0, distance];
Vector3 pos = Vector3.Transform(Vector3.Zero, viewMatrix);
Vector3 pos = viewMatrix.Translation;
Vector3 pos = new Vector3(viewMatrix.M41, viewMatrix.M42, viewMatrix.M43);

It seems like the rotation information is being lost somehow. The strange thing is that the viewMatrix code works perfectly for positioning the camera!

+1  A: 

Once again, I figure out the problem within seconds of posting the question:

I needed to invert the view matrix. The rotation info was being lost because it plays no part in the distance calculation until the view matrix is inverted. The rotation was at the wrong "end" of the transformation.

Vector3 pos = Vector3.Transform(Vector3.Zero, Matrix.Invert(viewMatrix));
Klay
+3  A: 

or to simplify slightly:

Vector3 pos = Matrix.Invert(view).Translation;

Steve H