- Home /
Chek multiple raycasts?
Hey,
Let's say that i cast 3 rays and i want to get the hit point of the first ray that hits, what would be the simplest way to do that?
Can this be simplified:
if ((hit1.collider != null || hit2.collider != null || hit3.collider != null))
{
if(hit1.collider != null)
hitPos = hit1.point;
else if(hit2.collider != null)
hitPos = hit2.point;
else if(hit3.collider != null)
hitPos = hit3.point;
//Do other stuff
}
What is the intention of the multiple raycasts? In most cases, using more than one raycast is a sign that you actually need a different type of cast. For example, if you are checking in front of the player, but want to check in a general view of the player, you can use a spherecast to traverse the forward trajectory. Or, you could use a targeting cone, and never raycast. If you need me to explain a targeting cone, I can.
it's just to check for a collision in front of the 2D player, i'm aware that there are other types of casts but for some reason i just went with three raycasts since i've never used anything else and it seemed like it would be more efficient.
Answer by Khena_B · Mar 06, 2018 at 04:00 AM
I decided to use a loop instead and do something like this to offset a single ray
for (int i = 0; i < raysCount; i++)
{
float offset = -0.25f * (i + 1);
RaycastHit2D hit = Physics2D.Raycast(transform.position + offset, transform.right, 0.35f, mask);
if (hit)
{
hitPos = hit.point;
//Do other stuff
}
}
Answer by Xarbrough · Mar 06, 2018 at 03:21 AM
You could try something like this:
using UnityEngine;
public class SomeClass : MonoBehaviour
{
private void FixedUpdate()
{
Ray ray1, ray2, ray3; // Create rays like you already do.
Vector3 hitPos;
if(GetFirstHit(out hitPos, ray1, ray2, ray3))
{
Debug.Log("First hit: " + hitPos);
}
}
private bool GetFirstHit(out Vector3 hitPos, params Ray[] rays)
{
RaycastHit hit;
for (int i = 0; i < rays.Length; i++)
{
if (Physics.Raycast(rays[i], out hit))
{
hitPos = hit.point;
return true;
}
}
return false;
}
}
Generally, whenever you do something more than twice, consider looping over a collection. In this case it can be very convenient to use the params keyword, which automatically creates an array for you.
Not sure why you are checking the colliders for null. It might be too late for me, but as far as I know you can only perform a Raycast against an existing collider, so it should work as shown in my code I believe.
You're right i don't need to check if it's null, i guess i could loop, i think i would just loop in Update and offset the same raycast to the 3 positions that i need and if the hit is true i'd use the hit pos, thanks for the suggestion
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
If raycast hits object with tag 2 Answers
c# Raycast going off at odd angles. Unity 5 2 Answers
WorldToScreenPoint returning ridiculously high number 1 Answer