- Home /
Is it possible to raycast multiple objects of the same tag (Enemy)
Here is what I got so far. I am trying to allow my bullets to pass through multiple targets(Zombies) instead of stopping at just one. In other words I will fire one bullet and this bullet will hit any zombie in line with my shot when I fire. So it will go through the first zombie and hit the next and possible stop at three or not.
if (hit.transform.tag == "Enemy")
{
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
GameObject bloodHole = Instantiate(Blood, contact, rotation) as GameObject;
if (Physics.Raycast(position, direction, out hit, Mathf.Infinity/*range*/, layerMask.value))
{
if (hit.rigidbody)
{
hit.rigidbody.AddForceAtPosition(force * direction, hit.point);
}
}
Physics.IgnoreCollision(hit.collider, GameObject.FindWithTag("Enemy").transform.root.GetComponent<Collider>());
}
Answer by Toadill9114 · Jan 05, 2017 at 05:56 AM
Okay well after looking around a bit I did find a now working solution to this. As you will see below in the code I had to create an array 'RaycastHit[] hits;' So that I could record all raycast hits with this tag and apply damage to them all at once within a for loop. So here is the chunk of code that made this work `hits = Physics.RaycastAll(position, direction, range);
RaycastHit[] hits;
hits = Physics.RaycastAll(position, direction, range);
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].transform.tag == "Enemy")
{
hits[i].collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
GameObject bloodHole = Instantiate (Blood, contact, rotation) as GameObject;
if (Physics.Raycast (position, direction, out hits[i], range, layerMask.value))
{
if (hits[i].rigidbody)
{
hits[i].rigidbody.AddForceAtPosition (force * direction, hit.point);
}
}
}
}
}
I'm looking for a similar logic. Like my game includes a gun that'd automatically identify and shoot the the enemies the raycast hits in the range provided. So can you help me that as in to make sure the ray doesn't hit the same enemy transform twice?
Thanks
Your answer
Follow this Question
Related Questions
Multiple Camera.main.ScreenPointToRay 1 Answer
How to destroy a gameObject when hit by Raycast? 4 Answers
Shotlock System 1 Answer
Ground Hugging Vehicle 1 Answer
wasd movement rigidbody no bouncing 0 Answers