Ahh, so you want an object to turn to be facing another object? Here is some C code I found for creating a look-at matrix. But better still, it actually has comments to say what it is doing!
Code:
//-----------------------------------------------------------------------------
// Name: buildLookAtMatrix()
// Desc: Creates a Left-Handed view matrix
//
// Building a View Matrix:
//
// 1. Subtract the camera's position from the position to look at, to
// create a view vector called 'l'.
// 2. Take the cross-product of the new view vector and the y axis of
// world space to get a right vector called 'r'.
// 3. The cross-product of vectors 'l' and 'r' will give you a up vector
// called 'u'.
// 4. Compute translation factors by taking the negative of the
// dot-product between the camera's position, called 'c', and our new
// orientation or basis vectors called u, r, and l.
//
// Here's what the final matrix should look like:
//
// | rx ux lx 0 |
// | ry uy ly 0 |
// | rz uz lz 0 |
// | -(r.c) -(u.c) -(l.c) 1 |
//
// Where r = Right vector
// u = Up vector
// l = Look vector
// c = Camera's world space position
// . = Dot-product operation
//-----------------------------------------------------------------------------
void buildLookAtMatrix( D3DXMATRIX *pOut,
const D3DXVECTOR3 &pEye,
const D3DXVECTOR3 &pAt,
const D3DXVECTOR3 &pUp )
{
D3DXVECTOR3 vRight; // New x basis
D3DXVECTOR3 vUp; // New y basis
D3DXVECTOR3 vView; // New z basis
// Subtract the camera's position from the viewer's position to
// create a direction or view vector for the camera. We'll call
// this vector, vView.
D3DXVec3Subtract(&vView, &pAt, &pEye);
// Normalize our new z basis vector.
D3DXVec3Normalize(&vView, &vView);
// Take the cross-product of the new direction vector and the
// x axis of the world space to get a right vector.
// We'll call this vector vRight.
D3DXVec3Cross(&vRight, &pUp, &vView);
D3DXVec3Normalize(&vRight, &vRight);
// The cross-product of the direction vector (vView) and the
// right vector (vRight) will give us our new up vector, which
// we'll call vUp.
D3DXVec3Cross(&vUp, &vView, &vRight);
// We now build the matrix. The first three columns contain the
// basis vectors used to rotate the view to point at the look-at
// point. The fourth row contains the translation values.
// Rotations are still about the eye point.
//
// m11 m12 m13 m14
// m21 m22 m23 m24
// m31 m32 m33 m34
// m41 m42 m43 m44
pOut->_11 = vRight.x;
pOut->_21 = vRight.y;
pOut->_31 = vRight.z;
pOut->_41 = -D3DXVec3Dot( &vRight, &pEye );
pOut->_12 = vUp.x;
pOut->_22 = vUp.y;
pOut->_32 = vUp.z;
pOut->_42 = -D3DXVec3Dot( &vUp, &pEye );
pOut->_13 = vView.x;
pOut->_23 = vView.y;
pOut->_33 = vView.z;
pOut->_43 = -D3DXVec3Dot( &vView, &pEye );
pOut->_14 = 0.0f;
pOut->_24 = 0.0f;
pOut->_34 = 0.0f;
pOut->_44 = 1.0f;
}
Bookmarks