Search code examples
mathmatrixxnaalgebra

Object orientation from normal


In my project I give an orientation to an object by applying the normal to the model matrix. My model matrix is the product of the scaling, rotation and translation matrices.

p22.Normal.Normalize();
obj.UpVector = p22.Normal;
obj.RightVector = Vector3.Cross(obj.ForwardVector, obj.UpVector);
obj.RightVector = Vector3.Normalize(obj.RightVector);

obj.ForwardVector = Vector3.Cross(obj.UpVector, obj.RightVector);
obj.ForwardVector = Vector3.Normalize(obj.ForwardVector);

Every time the object is updated the model matrix is calculated. But because of that I am loosing the orientation of the object, since the rotation matrix doesn't contain information about the orientation. Besides when I apply the normal to the model matrix, the object looses its scale.

Orientation's Up vector to be the terrain's normal, so that covers one axis. The other two can be calculated using cross products.Object facing direction (Forward) and the terrain's normal (Normal). Since the cross product produces a vector that is perpendicular to both vectors, I can calculate the Right vector.

I tried to apply the above solution to the rotation matrix but it gives the wrong result. How do I apply the normal to the rotation Matrix?

Sample:
Object.Scale(10,new Vector3(1,0,0));
Object.Translate(0,10,10);
Object.Update() is equal to modelMatrix=scaleMatrix*rotationMatrix*translationMatrix;
...
*calculeting normal from highmap*
...

p22.Normal.Normalize();
modelMatrix.UpVector = p22.Normal;
modelMatrix.RightVector = Vector3.Cross(obj.ForwardVector, obj.UpVector);
modelMatrix.RightVector = Vector3.Normalize(obj.RightVector);

modelMatri.ForwardVector = Vector3.Cross(obj.UpVector, obj.RightVector);
modelMatri.ForwardVector = Vector3.Normalize(obj.ForwardVector);
//the scale is lost.

object.Translate(10,10,10)
object.Update(); //orientation applied to model matrix is lost.

The whole question is why applying normal to rotation matrix doesn't give same result


Solution

  • Stave H comment gave me an idea what I was doing wrong. In my case Rotation matrix contains 2D rotation without inclination! After adding additional matrix everything works correctly.

        public void Update()
        {
            ModelMatrix = scaleMatrix * (orientationMatrix * rotateMatrix) * translateMatrix;
    
        }