Working with objects within a spherical radius

Bit of a noob here, but my overall aim is to put together a JS script which handles applying damage from a missile/bomb detonation in 3d space. Gameobjects should block damage from being applied to other gameobjects “behind” them, unless the nearer gameobject is destroyed by the blast; in which case the gameobject behind is damaged as normal. The gameobjects being hit will have some sort of collider component attached.

Basic pseudo code goes a little something like this:

If the nearer gameobject is destroyed it no longer exists when the further away gameobject has it’s turn in the foreach loop, there’s no need to do anything if the target is not returned by the raycast as the blocking gameobject has already had it’s turn in the loop.

Looking at the scripting reference I’ve found Physics.OverlapSphere which would appear to do the first step of finding all the colliders in the blast radius… but it has the following note:

I’m a little confused as to what that means… is it something that’s going to affect my intended usage?

Haven’t quite got to learning about arrays in unity yet, but since I’m asking and it’s the next step to work out: will I need to write a function to handle the returned array sorting? or does unity have something that handles array sorts already?

It shouldn’t, especially since you’re planning to do some further testing using raycasts and whatnot.

A bounding volume is the smallest box that is aligned to the global xyz axes and that completely contains the object inside its volume. By that definition it’s always going to be equal to or larger than the object’s actual collider. So while not as accurate as a collider, it should be good enough for your purpose.

HTH

Most of the standard container types have a sort method. I think a builtin array is the exception. Dictionaries for instance allow for a custom comparison in the sort method. For the love of god try to stay away from the unity Array class as it’s p slow.

I’m not sure you’re going to have an easy time trying to sort arbitrary 3d points returned by the OverlapSphere test though.

What I’d do is get your list of possibly affected objects via the OverlapSphere and then do RaycastAll against each object result, starting from the explosion point.

These RaycastAll results you’ll need to sort by distance to find out which objects are behind others. You might speed this up by ignoring object results that you’ve already found to be in line with something else. Then you can do your fancy “is dude in front of me blow up” type checks

ah ok, so the objects might not quite be in range. I was going to use infinite raycasts since the range had already been checked but it sounds like it’d be best to include the range in the raycasts to catch things on the edge of the blast clipping a bounding box corner or something.

I think avoiding infinite raycasts is always a good idea, at from a performance point of view.