Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XNA: get Vector3 from Matrix

Tags:

c#

matrix

xna

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!

like image 711
Klay Avatar asked Apr 19 '26 04:04

Klay


1 Answers

or to simplify slightly:

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

like image 106
Steve H Avatar answered Apr 21 '26 17:04

Steve H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!