質問

What rotation Matrix can I use to get my Model face a certain point?

My model is a character, and I want it to face the camera position.

I tried Matrix.LookAt, but it doesn't work.

役に立ちましたか?

解決

Let's assume that lookVector is the vector in model space that defines the view direction of the character. Usually this is one of the principal axes (e.g. the z-axis). Let's further assume that the character is positioned at characterPosition and that the target point is target.

The view direction towards the target in world space is

var view = target - characterPosition;

Now all we need to do is find a rotation matrix that maps lookVector to view. The solution is not unique, but we are looking for the solution with a minimal rotation angle.

The rotation axis can be found with the cross product, the rotation angle with the dot product:

var rotationAxis = Vector3.Cross(lookVector, view);
var rotationAngle = (float)Math.Acos(Vector3.Dot(lookVector, view) / lookVector.Length() / view.Length());

Now we can construct the rotation matrix:

var rotationMatrix = Matrix.CreateFromAxisAngle(rotationAxis, rotationAngle);

他のヒント

NO Wait! Matrix.CreateLookAt Works!

Think you have only used something like Matrix.CreateLookAt(Ship.Position, Target.Position, Ship.ModelRotation.Up)

But you have to add a Matrix.CreateTranslation to get it work. Or it will change it's shape instead of rotation!

This is the code

Ship.ModelRotation = Matrix.CreateTranslation(Ship.Position) * Matrix.CreateLookAt(Ship.Position, Target.Position, Ship.ModelRotation.Up)

I was in a serious trouble with this in two days. But this stupid code sloved that

Edit:

I don't know why, but this is the code working for me currently

Ship.ModelRotation = Matrix.invert( Matrix.CreateTranslation(Ship.Position) * Matrix.CreateLookAt(Ship.Position, Target.Position, Ship.ModelRotation.Up))

Note - This is a Visual basic code; Think you could just make it into C#

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top