Aligning a vehicle model to terrain RRS feed

  • Question

  • Hello


    I'm making a game where I have a vehicle driving over a terrain. I'm trying to rotate the vehicle so that it is aligned to the terrain as you drive around.


    I have the vehicle driving around and I'm adjusting the Y value so that its at the right height.


    Also, so far, I have extracted the nearest triangle from the terrain mesh and calculated its normal, but I can't figure out how to rotate the vehicle so that it is pointing in the right direction and is aligned with the terrain (i.e. the bottom of the vehicle is paralell with the terrain at that point)


    Any help with this would be greatly appreciated.



    Friday, May 4, 2007 12:58 PM


  • Hi, try this:


    // Obtain model "normal" from current rotation quaternion (or rotation matrix)

    Vector3 currentNormal = Matrix.CreateFromQuaternion(m_Rotation).Up;

    // Obtain triangle normal

    Vector3 newNormal = tri.Normal;

    // Obtain axis between two normals, it will be the rotation axis

    Vector3 axis = Vector3.Normalize(Vector3.Cross(currentNormal, newNormal));

    // Calc angle between normals

    float angle = (float)Math.Acos(Vector3.Dot(currentNormal, newNormal));

    if (angle != 0.0f)


    // Create a quaternion with the rotation difference between normals

    m_Inclination = Quaternion.CreateFromAxisAngle(axis, angle);




    m_Inclination = Quaternion.Identity;


    // Calc final transform

    m_ModelSpace = Matrix.CreateScale(m_Scale);

    m_ModelSpace *= Matrix.CreateFromQuaternion(m_Rotation);

    m_ModelSpace *= Matrix.CreateFromQuaternion(m_Inclination);

    m_ModelSpace *= Matrix.CreateTranslation(m_Position);


    If you want you can apply some slerp to make the transitions between triangles more realistic.


    You can see the results of this code in www.codeplex.com/tanksgame



    Friday, May 4, 2007 2:16 PM