# Moving a object directly towards another object?

## Recommended Posts

FounderSim    248

I am assuming some sort of calculations with angle's will come into play here..

Basicly, I am shooting a tank from 10,10, and I got another object at example: 400, 420 on a map. I am trying to get my missle to fly in that direction. At first I was thinking, I could just fly the bullet from 10,10 to 400,420 by calculating the difference in x,y, but my missle would still not be correctly facing the target.

##### Share on other sites
Finalspace    1147

Much better is computing the direction and magnitude separatly:

- Get the difference between those positions and calculate the magnitude of it pj - pi.

- Normalize the difference, by dividing it by its magnitude - this gives you the unit vector/direction

- Initialize the velocity of the rocket to = Normal * Magnitude / DT. (DT = Delta time in seconds - for example 0.016 - 60 fps)

- Initialize the position to (10, 10)

Now its just a matter of simple euler integration to let the rocket fly :-)

rocket velocity += rocket acceleration * DT (In your case acceleration is zero)

rocket position += rocket.velocity * DT

Also with damping enabled of your integrated velocity, you can achieve a speed increasing or decreasing rocket.

rocket velocity += rocket acceleration * DT (In your case acceleration is zero - so you can skip this step)

rocket velocity *= 1.025 // Slight speed-increase over time

rocket position += rocket.velocity * DT

Edited by Finalspace

##### Share on other sites

Are you using a physics engine (e.g. Box2D, Chipmunk, etc.) or are you doing this by controlling the positions of a sprite as your "moving thing"?

##### Share on other sites
Brain    18906

Something you might have overlooked is that the target the missile is moving towards is also moving. The target position must be re-calculated. I suggest not doing this every frame, but doing this every couple of seconds maybe?

This gives the target of the missile a fair chance to evade if they are fast and maneuverable enough.

I once wrote a similar system to this which had homing missiles of a similar nature, the only difference was that the missiles would always go towards the nearest target, so if during the process of seeking out an enemy another got too close, they would go for that one instead. I used simple pythagoras for that to calculate which enemy was closest "as the crow flies".

Let me know if you have any questions!