Advertisement
MysteryGM

Unity_AxisAlignedPolyCheck

Jun 22nd, 2021
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class AxisAlignedPoly
  6. {
  7.     public static bool ContainsPoint(Transform[] polyPoints, Transform Target)
  8.     {
  9.         var j = polyPoints.Length - 1;
  10.         var inside = false;
  11.         Vector3 p = Target.transform.position;
  12.  
  13.         for (int i = 0; i < polyPoints.Length; j = i++)
  14.         {
  15.             var pi = polyPoints[i].transform.position;
  16.             var pj = polyPoints[j].transform.position;
  17.             if (((pi.z <= p.z && p.z < pj.z) || (pj.z <= p.z && p.z < pi.z)) &&
  18.                 (p.x < (pj.x - pi.x) * (p.z - pi.z) / (pj.z - pi.z) + pi.x))
  19.                 inside = !inside;
  20.         }
  21.         return inside;
  22.     }
  23. }
  24.  
  25. public class FenceIn : MonoBehaviour
  26. {
  27.     public Transform[] FencePoints;
  28.     public GameObject Target;
  29.  
  30.     Material TargetMaterial;
  31.  
  32.     void Start()
  33.     {
  34.         TargetMaterial = Target.GetComponent<MeshRenderer>().material;
  35.     }
  36.  
  37.     private void Update()
  38.     {
  39.         if (AxisAlignedPoly.ContainsPoint(FencePoints, Target.transform))
  40.         {
  41.             TargetMaterial.SetColor("_BaseColor", Color.green);
  42.         }
  43.         else
  44.         {
  45.             TargetMaterial.SetColor("_BaseColor", Color.red);
  46.         }
  47.  
  48.         //DrawConnections(FencePoints);
  49.     }
  50.  
  51.     public void DrawConnections(Transform[] polyPoints)
  52.     {
  53.         int index = 0;
  54.         while (index < polyPoints.Length-1)
  55.         {
  56.             Vector3 PointA = polyPoints[index].position;
  57.             PointA.y = 0;
  58.             Vector3 PointB = polyPoints[index + 1].position;
  59.             PointB.y = 0;
  60.  
  61.             Debug.DrawLine(PointA, PointB);
  62.             index += 1;
  63.         }
  64.         if (index == polyPoints.Length-1)
  65.         {
  66.             Vector3 PointA = polyPoints[0].position;
  67.             PointA.y = 0;
  68.             Vector3 PointB = polyPoints[index].position;
  69.             PointB.y = 0;
  70.  
  71.             Debug.DrawLine(PointA, PointB);
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement