Search code examples
c++mathdirectx-9directiond3dx

Calculate a vector between 2 D3DXVECTOR3 independent of distance


So here's my scenario: I have a spaceship game, each spaceship can target another ship and fire torpedoes and the torpedo needs a directional vector to travel along, the vector needs to be independent of the distance.

I'm looking to create a method that returns a D3DXVECTOR3 constructed like so:

D3DXVECTOR3 TargetVector(D3DXVECTOR3 *target, D3DXVECTOR3 *firer)

Has anyone got experience in this matter? It would be great if anyone could even point me towards any decent, easy to understand D3D mathematics tutorials as all I have found so far is based on rendering images rather than mathematical equations.

Thanks!

-Ryan


Solution

  • If you want a direction vector that starts from firer and points at target just subtract firer from target ie :

    direction = target - firer;
    

    There is D3DXVec3Subtract for it in D3DX lib.

    If you want to have a unit normal, which is a vector that has a length of 1 then normalize it with D3DXVec3Normalize.

    So you will have :

    D3DXVECTOR3 TargetVector(D3DXVECTOR3 *target, D3DXVECTOR3 *firer)
    {
        D3DXVECTOR3 direction;
        D3DXVec3Subtract(&direction, target, firer);
    
        D3DXVec3Normalize(&direction, &direction);
        return direction;
    }