Guest User

Object Visibiliy Check

a guest
Jan 15th, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | Source Code | 0 0
  1. using UnityEngine;
  2.  
  3. public static class VisibilityHelper
  4. {
  5.     private static float DistantRadiusToAngle(float distance, float radius)
  6.     {
  7.         return Mathf.Asin(radius / distance) * Mathf.Rad2Deg;
  8.     }
  9.  
  10.     public static bool IsObjetVisible(Vector2 viewPosition, Vector2 viewDirection, float viewDistance, float viewAngle, Vector2 objectPosition, float objectRadius)
  11.     {
  12.         Vector2 delta = objectPosition - viewPosition;
  13.         float distanceToObject = delta.magnitude;
  14.  
  15.         //If view circle and object circle do not intersect - then object is out of view range
  16.         if (viewDistance + objectRadius < distanceToObject)
  17.             return false;
  18.  
  19.         float angleToObject = Vector2.Angle(viewDirection, delta);
  20.  
  21.         //Since out calculations are using decline from view direction - we need only half of our view angle
  22.         float halfViewAngle = viewAngle / 2f;
  23.         //We are converting object radius to angle, using trigonomentry
  24.         float objectRadiusAsAngle = DistantRadiusToAngle(distanceToObject, objectRadius);
  25.  
  26.         //If object is declined too far from our view direction - then it is outside of our viewport
  27.         if ((halfViewAngle + objectRadiusAsAngle) < angleToObject)
  28.             return false;
  29.  
  30.         return true;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment