It's easier than that.
Code:
struct Vector2D
{
float x;
float y;
};
void GetVectorTo(Vector2D Start, Vector2D End, Vector2D &Result)
{
float vector_x=Start.x-End.x;
float vector_y=Start.y-End.y;
float totaldist=sqrt((vector_x*vector_x)+(vector_y*vector_y));
float oneOverDist=1.0f/totaldist;
Result.x=vector_x*oneOverDist;
Result.y=vector_y*oneOverDist;
}
For DirectX using the D3DX library:
Code:
void GetVectorTo(D3DXVECTOR2 Start,D3DXVECTOR2 End,&D3DXVECTOR2 Result)
{
D3DXVECTOR2 VectorFromStartToEnd;
D3DXVec2Subtract(&VectorFromStartToEnd,&Start,&End);
D3DXVec2Normalize(&Result,&VectorFromStartToEnd);
}
This function returns a normalized or unit vector from Start to End. All vectors will lie on a unit circle and thereby can be used to increment your object each frame.
The use for this code is:
Code:
class Object2D
{
Vector2D Position;
float Speed;
float Angle;
...
...
};
void Object2D::ComputeVectorToTarget(Object2D Target)
{
Vector2D Result;
GetVectorTo(Position,Target.Position,Result);
VelocityVector=Result;
Angle=atan2(VelocityVector.x,VelocityVector.y);
}
void Object::Update(float _frameTimeDelta)
{
Position.x+=(VelocityVector.x*Speed)*_frameTimeDelta;
Position.y+=(VelocityVector.y*Speed)*_frameTimeDelta;
}
So to get the vector from Object/Point A to Object/Point B
1. Create a Vector V from Object A to Object B by subtracting them.
2. Compute length of Vector V by using distance formula.
3. Divide each element of Vector V by the distance you just computed - or in simpler terms normalize Vector V.
I use oneOverDistance because dividing by distance is the same as multiplying by its reciprocal. A floating point multiplication is much faster than a floating point divide.
The angle is computed by taking the arc tanget of y over x. The C math function atan2 will do this for you. And sorry for using a class and other C++ code on a C board but people will get over it.
cos(theta) = (5 - x)/sqrt((5 - x) *(5 - x) + (3 - y) * (3 - y)) and
sin(theta) = (3 - y)/sqrt((5 - x) *(5 - x) + (3 - y) *( 3 - y))
Essentially the same thing with (5-x) being the x component of Vector V and (3-y) being the y component of Vector V.