# AI: aiming towards a moving target

I would like to show a possible solution that I worked on for the aiming towards a moving target problem. Let P be the player, E the enemy, S the shot. P shoots towards E, but in the meantime E may be moved.

Let’s put ourselves in the reference system of P and consider polar coordinates. Let’s calculate the normal velocity of E against P. Let’s assume that the distance between P and E is constant over time.

We can compute the time that S takes to reach E from P. Then, we can use this time to compute the new angle of E against P.

In this way, we are able to make a rough prevision of where E will be when it will be reached by S. P just needs to shoot S in that direction.

Enjoy!

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// argument0: P // argument1: E // argument2: shot speed var vx_rel=argument1.vx-argument0.vx; var vy_rel=argument1.vy-argument0.vy; var radius=point_distance(argument0.x,argument0.y,argument1.x,argument1.y); var ang=point_direction(argument0.x,argument0.y,argument1.x,argument1.y); var time=radius/argument2; var m=point_distance(0,0,vx_rel,vy_rel); var d=point_direction(0,0,vx_rel,vy_rel); d-=ang; var vt=m*sin_deg(d); var corr=(vt*time)/radius; var ang2=ang+radtodeg(corr); var xColl=argument0.x+radius*cos_deg(ang2); var yColl=argument0.y-radius*sin_deg(ang2); var ar; ar[0]=ang2; ar[1]=time; ar[2]=xColl; ar[3]=yColl; return ar; |