- Home /
Stop raycast from hitting same gameObject twice
I've created a script now that can detect all enemies in a radius. In order to stop enemies who are behind walls from being harmed by the explosion radius, a raycast is sent out in order to ensure that it hits an enemy and not a wall. Unfortunately, if there are two enemies in the same direction, then two raycasts are going to be sent towards the same enemy, thus hitting them multiple times.
My question is: How can I stop an enemy standing in front of another enemy from being hit by a raycast that is intended to hit the object behind it?
if(collision.gameObject.tag == "Enemy") { collision.gameObject.SendMessage("takeDamage", 125); }
grenadeBody.velocity = Vector3.zero;
Collider[] collisionsInRadius = Physics.OverlapSphere(transform.position, 3f); //Needs layermask so it only detects gameobjects with enemy tag.
for(int i = 0; i < collisionsInRadius.Length; i++)
{
Ray explosionRay = new Ray(transform.position, collisionsInRadius[i].transform.position - transform.position);
if (Physics.Raycast(explosionRay, out RaycastHit explosionHit, 3f))
{
if(explosionHit.collider.gameObject.tag == "Enemy")
{
collisionsInRadius[i].gameObject.SendMessage("takeDamage", 225);
}
}
}
//play explosion effect.
Destroy(this.gameObject);
Answer by Zaeran · May 17, 2019 at 04:23 PM
You'd likely have to do a Physics.RaycastAll, and then order the hit colliders by distance. Iterate through from closest to furthest, and stop when you hit a wall.
So does Physics.RaycastAll send out a ray and the ray continues regardless of the number of times it hits an object?
if that's true, I could sort them by distance, and then apply damage to all gameObjects with tag enemy, and if the distance of a wall is closer than the distance of one of the enemies, then ignore whatever is past it right?
Thanks.
Actually, never$$anonymous$$d. This doesn't actually answer my question. $$anonymous$$y script already did that as I realize now, except it did raycast all. This still doesn't solve my issue with an enemy having the potential to be hit multiple times.
Answer by xxmariofer · May 20, 2019 at 03:35 PM
just create a list on Colliders
List<Collider> colliders = new List<Collider>();
change raycast for raycastall
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, collisionsInRadius[i].transform.position - transform.position, 100.0F);
foreach(RaycastHit hit in hits) {
if(hit.collider.gameObject.tag == "Enemy" && !colliders.Contains(hit.collider)) { collisionsInRadius[i].gameObject.SendMessage("takeDamage", 225); colliders.Add(hit.collider); }
}