- using UnityEngine;
- using System.Linq;
- using System.Collections;
- public class Test : MonoBehaviour
- {
- public Transform testComparePoint;
- public Transform[] pointsArray;
- public floatheight =4;
- public bool IsInRange(Vector3 comparePoint)
- {
- if(comparePoint !=null)
- {
- varflag =true;
- flag &= comparePoint.y <= height;
- flag &= comparePoint.y >= -height;
- flag &= IsConcaveContain2D(pointsArray, comparePoint);
- if (flag)
- return true;
- }
- return false;
- }
- public bool IsConcaveContain2D(Transform[] points, Vector3 compare)
- {
- const floatVIRTUAL_RAYCAST_LEN =100000;
- varcomparePoint = (points[1].localPosition + points[0].localPosition) *0.5f;
- varoriginPoint = compare;
- comparePoint += (comparePoint - originPoint).normalized * VIRTUAL_RAYCAST_LEN;
- intcount =0;
- for(inti =0; i < points.Length; i++)
- {
- vara = points[i % points.Length];
- varb = points[(i +1) % points.Length];
- varr = IsLineSegmentIntersection(a.localPosition, b.localPosition, originPoint, comparePoint);
- if(r) count++;
- }
- returncount %2==1;
- }
- public bool IsLineSegmentIntersection(Vector3 a, Vector3 b, Vector3 c, Vector3 d)
- {
- varcrossA = Mathf.Sign(Vector3.Cross(d - c, a - c).y);
- varcrossB = Mathf.Sign(Vector3.Cross(d - c, b - c).y);
- if(crossA == crossB)return false;
- varcrossC = Mathf.Sign(Vector3.Cross(b - a, c - a).y);
- varcrossD = Mathf.Sign(Vector3.Cross(b - a, d - a).y);
- if(crossC == crossD)return false;
- return true;
- }
- void OnDrawGizmos()
- {
- if(pointsArray ==null)return;
- if(testComparePoint !=null)
- {
- varcomparePoint = transform.InverseTransformPoint(testComparePoint.transform.position);
- if (IsInRange(comparePoint))
- {
- Gizmos.color = Color.red;
- }
- }
- varcacheMatrix = Gizmos.matrix;
- Gizmos.matrix = transform.localToWorldMatrix;
- for(inti =0; i < pointsArray.Length; i++)
- {
- vara = pointsArray[i];
- varb = pointsArray[(i +1) % pointsArray.Length];
- if(a ==null)continue;
- if(b ==null)continue;
- varminA = a.localPosition;
- varminB = b.localPosition;
- varmaxA = a.localPosition;
- varmaxB = b.localPosition;
- minA.y = -height;
- minB.y = -height;
- maxA.y = height;
- maxB.y = height;
- Gizmos.DrawLine(minA, minB);
- Gizmos.DrawLine(maxA, maxB);
- Gizmos.DrawLine(minA, maxA);
- Gizmos.DrawLine(minB, maxB);
- }
- Gizmos.color = Color.clear;
- Gizmos.matrix = cacheMatrix;
- }
- }
来源: http://www.bubuko.com/infodetail-2091679.html