I looked around, but all answers are too complex for my needs.
I have a sphere called RollerAgent, and a cube called Target. If there is no object between the straight line from the Sphere to the Cube I want the boolean to return true. I tried searching the internet, but all the answers were too complex for my needs.
I have a sphere called RollerAgent, which I can roll around, and a cube called target which I want to detect.
I simply need for when there is not an object between the sphere and the cube, a boolean to return true.
1 Answer
1
using System.Linq;
using UnityEngine;
public class LineOfSightTester : MonoBehaviour
{
[SerializeField] Collider[] _collidersToIgnore = new Collider[0];
[SerializeField] Transform _P0, _P1;
void Update ()
{
Vector3 p0 = _P0.position;
Vector3 p1 = _P1.position;
bool result = IsLineSegmentFreeOfColliders( p0 , p1 , _collidersToIgnore );
}
static bool IsLineSegmentFreeOfColliders ( Vector3 p0 , Vector3 p1 , Collider[] ignored )
{
var hits = Physics.RaycastAll( p0 , p1-p0 );
foreach( RaycastHit hit in hits )
{
Collider hitCollider = hit.collider;
if( !ignored.Contains(hitCollider) )
{
Debug.DrawLine( p0 , hit.point , Color.red );
return false;
}
}
Debug.DrawLine( p0 , p1 , Color.white );
return true;
}
}