#How to keep an object as "visible" when partially obscured by obstacle?
1 messages · Page 1 of 1 (latest)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FieldOfView : MonoBehaviour
{
public float viewRadius;
[Range(0,360)]
public float viewAngle;
public LayerMask targetMask;
public LayerMask obstacleMask;
public Camera cam;
public List<Transform> visibleTargets = new List<Transform>();
private bool IsVisible(Transform target)
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cam);
Vector3 dir = target.position - cam.transform.position;
dir = dir.normalized;
if (GeometryUtility.TestPlanesAABB(planes , target.GetComponent<Collider>().bounds))
return true;
else
return false;
}
void FindVisibleTargets()
{
for(int i = 0; i < visibleTargets.Count; i++) {
visibleTargets[i].GetComponent<Renderer>().material.SetColor("_Color", Color.red);
}
visibleTargets.Clear();
Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);
for(int i = 0; i < targetsInViewRadius.Length; i++) {
Transform target = targetsInViewRadius[i].transform;
Vector3 dirToTarget = (target.position - transform.position).normalized;
if(IsVisible(target)){
float dstToTarget = Vector3.Distance(transform.position, target.position);
if(!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask) || target.GetComponent<Renderer>().isVisible) {
visibleTargets.Add(target);
target.GetComponent<Renderer>().material.SetColor("_Color", Color.black);
}
}
}
}
void Start()
{
}
// Update is called once per frame
void Update()
{
FindVisibleTargets();
}
}
Currently this code works except for when the objects are peaking out the sides
Ex:
The only realistic option is:
if(!Physics.Raycast(transform.position, dirToTarget, dstToTarget, obstacleMask)```
Do more raycasts
right now you're only raycasting to the object's pivot
you'll want to do more samples than that
for example raycast to the corners
see if you can see them
I recommend Physics.Linecast for this - it's simpler for this use case
Over the original raycast as well or just the corners?
up to you
whatever you feel is a good enough sample to decide that if none of those things are visible, the object is not visible
Thanks this worked!