码迷,mamicode.com
首页 > 其他好文 > 详细

2D空间中判断一点是否在三角形内

时间:2016-11-29 07:12:46      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:sig   实现原理   cto   com   unity3d   triangle   tor   rac   generic   

本来打算做三角形填充多边形,但需要用到耳切法正在看。所以先研究了这个

要注意如果是XY坐标轴的2D空间,要取差乘分量z而不是y。

 

实现原理是,将三角形ABC三个边(AB,BC,CA)分别与比较点判断差乘,如果这3个差乘结果表示的方向一致,说明就在三角形内。

 

效果:

技术分享

 

 

代码(Unity3D):

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TriangleCollider : MonoBehaviour
{
    public const float ERROR = 0.05f;
    public Transform trianglePoint1;
    public Transform trianglePoint2;
    public Transform trianglePoint3;
    public Transform comparePoint;


    public bool IsContract(Vector3 comparePoint)
    {
        var dir1 = trianglePoint2.position - trianglePoint1.position;
        var dir2 = trianglePoint3.position - trianglePoint2.position;
        var dir3 = trianglePoint1.position - trianglePoint3.position;

        var cross1 = Mathf.Sign(Vector3.Cross(dir1, comparePoint - trianglePoint1.position).y);
        var cross2 = Mathf.Sign(Vector3.Cross(dir2, comparePoint - trianglePoint2.position).y);
        var cross3 = Mathf.Sign(Vector3.Cross(dir3, comparePoint - trianglePoint3.position).y);

        var dir = cross1 == cross2 ? cross3 : cross1 == cross3 ? cross2 : cross1;

        cross1 = Mathf.Sign(Vector3.Cross(dir1, comparePoint - trianglePoint1.position).y + -dir * ERROR);
        cross2 = Mathf.Sign(Vector3.Cross(dir2, comparePoint - trianglePoint2.position).y + -dir * ERROR);
        cross3 = Mathf.Sign(Vector3.Cross(dir3, comparePoint - trianglePoint3.position).y + -dir * ERROR);

        return cross1 == cross2 && cross2 == cross3;
    }

    void OnDrawGizmos()
    {
        if (comparePoint == null) return;

        var oldColor = Gizmos.color;

        if (IsContract(comparePoint.position))
            Gizmos.color = Color.red;

        Gizmos.DrawLine(trianglePoint1.position, trianglePoint2.position);
        Gizmos.DrawLine(trianglePoint2.position, trianglePoint3.position);
        Gizmos.DrawLine(trianglePoint3.position, trianglePoint1.position);

        Gizmos.color = oldColor;
    }
}

 

为了加误差,所以多做了3次差乘。不过使用起来还算可以

2D空间中判断一点是否在三角形内

标签:sig   实现原理   cto   com   unity3d   triangle   tor   rac   generic   

原文地址:http://www.cnblogs.com/hont/p/6111813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!