Search code examples
2dintersectionpredict

2d game : fire at a moving target by predicting intersection of projectile and unit


Okay, this all takes place in a nice and simple 2D world... :)

Suppose I have a static object A at position Apos, and a linearly moving object B at Bpos with bVelocity, and an ammo round with velocity Avelocity...

How would I find out the angle that A has to shoot, to hit B, taking into account B's linear velocity and the speed of A's ammo ?

Right now the aim's at the current position of the object, which means that by the time my projectile gets there the unit has moved on to safer positions :)


Solution

  • First rotate the axes so that AB is vertical (by doing a rotation)

    Now, split the velocity vector of B into the x and y components (say Bx and By). You can use this to calculate the x and y components of the vector you need to shoot at.

    B --> Bx
    |
    |
    V
    
    By
    
    
    Vy
    ^
    |
    |
    A ---> Vx
    

    You need Vx = Bx and Sqrt(Vx*Vx + Vy*Vy) = Velocity of Ammo.

    This should give you the vector you need in the new system. Transform back to old system and you are done (by doing a rotation in the other direction).