# How to rotate an object so that it is aligned with a vector?

I have the following Scenario: Two moving objects (A and B in the picture) need to appear "connected" by a third one (C in the picture). I set the position of the connecting object C as "halfway" between A and B, but how do I rotate it in such a way that it is alined with the vector that connects them (i.e. the result of A - B)? I've tried with D3DXMatrixLookAtRH(&rotate, &eye, &look, &UP_VECTOR) where eye = (0,0,0),look = A's position - B's position and using the rotate matrix as a rotation matrix for C but the result doesn't look as what I expect.

• What exactly is wrong with result of LookAt? Try passing C's position as &eye and either A's or B's position as &look, then apply whole matrix to C. Alsho check if you are using correct 'up' axis (DirectX uses +Y). Dec 23, 2014 at 8:27

D3DXMatrixLookAtRh is a function for making a view matrix (scene camera analogy) which happens to be the inverse of a world matrix for an object located and rotated the same as the view matrix.

So invert the result of your matrix and use the halfway point for eye, and give the function a look at position instead of a direction it is looking.

pseudo code:

//aPos == position of object A
//bPos == position of object B
//cPos == position of object C
cPos = bPos + (.5 * (aPos - bPos));

D3DXMatrix* invRotate;

D3DXMatrixLookAtRh(&invRotate, &cPos, &aPos, UP_VECTOR);

D3DXMatrixInverse(&rotate, null, &invRotate);
//rotate is now the world matrix for object C