I’m trying to set up an explosion cover system in my game, where if a rocket or something blows up, anything caught in its blast radius but standing behind cover won’t take damage. The following image demonstrates a typical scenario. The player will fire a rocket between the two enemies at the wall, and because the overlap sphere’s radius is large enough, both enemies will be caught in the explosion and take damage based on proximity to the blast’s epicenter.
However, although I’m checking for cover using pretty standard raycasting techniques, the rocket incorrectly detects that the wall it collided with somehow provides cover to the two enemies.
public override void Detonate()
{
//Instantiate blast prefab
var colliders = Physics.OverlapSphere(transform.position, _blastRadius);
CheckCollidersForBlastDamage(colliders);
Destroy(gameObject);
}
private bool ColliderHasExplosionCover(Collider collider)
{
//Raycast from center of blast to target; should get list of everything ray hits, and if an obstruction is between the blast epicenter and target, no damage is taken
int layerMask = 1 << 8; //Bit shift index of layer to get bit mask
//layerMask = ~layerMask; //Collide against everything except specified layer; ~ inverts bitmask
RaycastHit hit;
var direction = transform.position - collider.transform.position;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(direction), out hit, Vector3.Distance(transform.position, collider.transform.position), layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(direction) * hit.distance, Color.yellow);
Debug.Log($"OBJECT {hit.collider.gameObject.name} IS PROVIDING COVER TO {collider.gameObject.name}");
return true;
}
return false;
}
What exactly am I doing wrong? The rocket, for the time being, is simply a capsule with a matching collider. Additionally, if you have better suggestions on how to determine whether or not something has cover from an explosion, post it.