Search code examples
mathmatrixdirectxgame-physics

car orientation on a plane


I am currently working on a simple car simulation on a plane in DirectX. I am having problems on orienting the car on the plane .
what i am doing is this...

D3DXMATRIX planeMat //matrix of the plane on which car is currently situated.
...

//calculating car rotation matrix (on XZ plane )
D3DXMATRIX carRot;
D3DXMatrixRotationY( &carRot , yaw );

//car up will same as plane
D3DXVECTOR3 carUp = D3DXVECTOR3( planeMat._12 , planeMat._22 , planeMat._32 );
//car lookat vector
D3DXVECTOR3 carLookat = D3DXVECTOR3( carRot._13 , carRot._23 , carRot._33 );
// calculating right vector
D3DXVec3Cross( &carRight , &carLookAt , &carUp );
D3DXVec3Normalize( &carRight , &carRight );
//calculating new lookat 
D3DXVec3Cross( &carLookAt , &carRight , &carUp );
D3DXVec3Normalize( &carLookAt , &carLookAt );

//car matrix
D3DXMATRIX carMat; D3DXMatrixIdentity( &carMat );
carMat._11 = carRight.x ;carMat._21 = carRight.y ;carMat._31 = carRight.z ;
carMat._12 = carUp.x ;carMat._22 =  carUp.y ;carMat._32 = carUp.z ;
carMat._13 = carLookAt.x ;carMat._23 = carLookAt.y ;carMat._33 = carLookAt.z ;
carMat._41 = carPos.x ;carMat._42 = carPos.y ;carMat._43 = carPos.z ;

I can't get car's rotation correct.
please help me.


Solution

  • The way you are setting & using components in your matrix doesn't look correct. For instance, in carMat the 3 basis vectors have the 2nd digit of the component constant but in the last one (carPos), the 1st digit of the component is constant. It's either one way or the other for all 4 rows/columns of the matrix.

    I believe the way you are setting the car's position (last row/column) is the correct way and the way you are doing the up, right, & lookat are incorrect. So, for instance, it should probably be like this:

    D3DXMATRIX carMat; D3DXMatrixIdentity( &carMat );
    carMat._11 = carRight.x ;carMat._12 = carRight.y ;carMat._13 = carRight.z ;//11, 12, 13 instead of 11, 21, 31 
    carMat._21 = carUp.x ;carMat._22 =  carUp.y ;carMat._23 = carUp.z ;
    carMat._31 = carLookAt.x ;carMat._32 = carLookAt.y ;carMat._33 = carLookAt.z ;
    carMat._41 = carPos.x ;carMat._42 = carPos.y ;carMat._43 = carPos.z ;
    

    Also, the way you populate the vectors carUp and carLookAt fom the components of planeMat & carRot suffers from the same issue.