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
}
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*, 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.
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
}
}