using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BorderTest : MonoBehaviour {
List<Line> lineList = new List<Line>();
Transform[] transTmp;
List<Vector2> vList = new List<Vector2>();
List<Line> nLine = new List<Line>();
int number;
int count = 0;
Vector2 vec = new Vector2(1, 2);
void Start () {
number = GameObject.Find("ListPoints").transform.childCount;
getChildren(number); // 点都放这个子物体下了,
// print(vList.Count);
getPointPairs(); // 获取组成线的两个点
test(new Vector2(6, 0)); // 拿这个点来进行测试
}
private void test(Vector2 vec1) {
foreach (var item in nLine)
{
if (item.hasCommomPoint(vec1, 0))
{
count = count + 1;
}
}
print(count);
if ((count % 2) == 1)
{
print("在里面");
GameObject obj = new GameObject();
obj.transform.position = vec1;
}
else
{
print("不在里面");
GameObject obj = new GameObject();
obj.transform.position = vec1;
}
}
private void getChildren(int num) {
for (int i = 0; i < num; i++)
{
Vector2 vec = GameObject.Find("ListPoints").transform.GetChild(i).position;
// Debug.Log(vec.ToString() + " " + GameObject.Find("ListPoints").transform.GetChild(i).gameObject.name);
vList.Add(vec);
}
}
private void getPointPairs() {
for (int i = 0, j = 0; i < vList.Count; j = ++i)
{
// print(i +" "+ (j + 1) % vList.Count);
Line line = new Line(vList[i], vList[(j + 1) % vList.Count]);
nLine.Add(line);
}
}
// Update is called once per frame
void Update () {
}
}
public class Line
{
public Vector2 pointLeft;
public Vector2 pointRight;
public double k;
public double b;
public Line(Vector2 vec1, Vector2 vec2) {
// Debug.Log(vec1 + " " + vec2);
if(vec1.x < vec2.x)
{
pointLeft = vec1;
pointRight = vec2;
}
else
{
pointLeft = vec2;
pointRight = vec1;
}
if ((vec1.x == vec2.x)) {
Debug.Log("???");
Debug.Log(vec1.ToString() + " " + vec2.ToString());
}
else {
this.k = (double)(pointRight.y - pointLeft.y) / (pointRight.x - pointLeft.x);
this.b = vec1.y - k * vec1.x;
Debug.Log(this.k);
// Debug.Log((pointRight.y - pointLeft.y) / (pointRight.x - pointRight.x));
}
}
public bool hasCommomPoint(Vector2 vec, float k1) {
float y = vec.y;
double x;
// Debug.Log(this.k + " " + this.b);
if (this.k != null) {
if (this.k == 0) {
if (pointLeft.y == vec.y) {
if (pointLeft.x <= vec.x && pointRight.x > vec.x) {
return true;
} else{
return false;
}
}
else
{
Debug.Log("K = 0 没有交点");
return false;
}
}
else
{
x = (y - this.b) / this.k;
if (pointLeft.x < x && x < pointRight.x)
{
return true;
}
else
{
Debug.Log("K != 0 交点 超限");
return false;
}
}
}
else
{
Debug.Log("没有K");
if ((pointLeft.y <= y && y <= pointRight.y) || (pointLeft.y >= y && y >= pointRight.y)) {
if (vec.x >= pointLeft.x) {
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
利用的理论基础:
从目标点向一个方向发一条线,若与目标图形的焦点个数为基数,则在内部,否则不在
但是有一下几个条件:
1.凹多边形:以上基础不适用,建议拆成突多边形来做
2.还有一种情况:
看图
注意:本例使用了Unity,只是为了取点数据。