How can i detect if the player is inside an explosion radius?

How can i detect if the player is inside an explosion radius?

I'm making a driving game, there are enemies which spawn on the side of road and when my player car gets close, they fire a rocket in front of the player. I need to detect if the car is within a certain radius of the explosion center. So when I can detect that I'm assuming I can then use rb.AddExplosiveForce to make the car fly a bit or something.
What is the recommended way to get the blast radius collider (or equivalent) and detect if the player is inside it?

Solutions/Answers:

Answer 1:

For an instantaneous radius check, you can use the OverlapSphere method like so:

Collider[] hits = Physics.OverlapSphere(
          explosionCenter,
          explosionRadius,
          layerMaskToCheck );

This gives you an array containing all colliders touched by the explosion’s spherical volume. You can then iterate through that array to apply forces & damage to their corresponding objects.

For better control over performance, you can use the NonAlloc version where you prepare a reusable buffer in advance, so it can fill that existing array with its results instead of allocating new ones and creating garbage to collect later.

However, if only the player is affected, then you can skip the physics queries entirely and just use a distance check to detect whether the Player object is within a given radius of the hit point:

 if((player.transform.position - explosionCenter)
   .sqrMagnitude < explosionRadius * explosionRadius)

(Here using a common trick of comparing squared values to skip an unnecessary square root operation — this isn’t terribly important if you’re only doing it a few times, just a habit a lot of us are in)

References