Search code examples
c#unity-game-enginecollision-detectioncomputational-geometry

Detecting possible projectile vs shield collision


I'm trying to detect, whether a projectile is going to hit a shield - and where will the collision happen.

enter image description here

On this image, you can see the situation. Though the A and B projectiles are in approximately the same distance from shield centre S, one of them will collide with the shield and other one will not.

enter image description here

Solution that is mathematically straightforward would use the mathematical equation of circle and the equation of the line of the projectile path.

With a pen and a paper, I can calculate that. However, I have a very bad experience with implementing analytic geometry directly.

Also, this would return positives for projectiles leaving the shield. How do I filter them?

enter image description here

Second approach, friends idea, is measuring the minimal distance between projectile path and the shield centre - if l is smaller than r, a collision happens.

It seems easier to implement, but doesn't let me know where will the collision happen.

I work in 2 dimensions. I'm using C# and the Unity Engine, however universal solutions are welcome.

The projectile is, of course, considered a point with zero size.


Solution

  • Use the parametric equation of the trajectory: X= X0 + t.P + X0, Y = t.Q + Y0 (starting from (X0, Y0) in direction (P, Q)).

    Plug this into the circle equation (X - Xc)^2 + (Y - Yc)^2 = R^2, and get:

    (t.P + Dx)^2 + (t.Q + Dy)^2 = (P^2+Q^2).t^2 + 2.(P.Dx+Q.Dy).t + Dx^2+Dy^2 = R^2.
    

    This is a quadratic equation in t. The shield is hit whenever there is a positive root.

    If your projectile has nonzero radius r, just imagine you deflate the projectile to 0 and inflate the target to R + r.