Search code examples
matrixgeometrydirectx-9

calculate look at matrix on terrain


hoping someone can help me. I have a go kart on a terrain, from which I get the position of the centre of the go kart, the left front wheel and the right front wheel. What I need is a matrix to rotate the kart so it sits flat on the terrain.

All vector3's. Forward is direction vector.

So far I have this but It's not working as expected

D3DXVECTOR3 cross, cross1;
    cross = kartposition - Lwheelposition;
    cross1 = kartposition - Rwheelposition;
    D3DXVec3Cross(&up, &cross, &cross1);
    D3DXVec3Normalize(&up, &up);

    D3DXVec3Cross(&right, &forward,&up);
    D3DXVec3Normalize(&right, &right);
    D3DXVec3Cross(&forward,  &up,&right);
    D3DXVec3Normalize(&forward, &forward);



    D3DXMatrixLookAtLH(&localtransform[0], &D3DXVECTOR3(0, 0, 0) ,&(forward), &up);

Any advise would be great.

Solved I believe.

Have change 2 lines to

cross = Lwheelposition-kartposition ; cross1 =Rwheelposition - kartposition ;

and added to the end

D3DXMatrixInverse(&localtransform[0],NULL,&localtransform[0]);

to invert the action of the look at function.


Solution

  • I have since revised and solved this by referring to

    (DirectX) Generating a rotation matrix to match a vector

    Final code is as follows.

    D3DXVECTOR3 cross, cross1;
            cross = Lwheelposition - kartposition;
            cross1 = Rwheelposition - kartposition;
            D3DXVec3Cross(&up, &cross, &cross1);
            D3DXVec3Normalize(&up, &up);
    
            D3DXVec3Cross(&right, &up,&forward);
            D3DXVec3Normalize(&right, &right);
            D3DXVec3Cross(&kartforward, &right, &up);
    localtransform[0]=D3DXMATRIX (right.x, right.y, right.z, 0.0f,
                up.x, up.y, up.z, 0.0f,
                kartforward.x, kartforward.y, kartforward.z, 0.0f,
                kartposition.x, kartposition.y, kartposition.z, 1.0f);
    

    Hope this is helpful.