判断点是否在三角形内
算法思想:利用向量叉积性质判断点和三角形边的相对位置关系。需要注意的是,在计算叉积之前需要先将三个顶点按顺时针或者逆时针方向排好序。
叉积相关概念和性质参见:
http://hi.baidu.com/zhubingn/item/cb63083e987b8cad134b14ab
http://en.wikipedia.org/wiki/Cross_product
代码如下:
#include <stdlib.h> #include <stdio.h> typedef struct _Point { int x, y; }Point; void swap(Point *p1, Point *p2) { int temp; temp = p1->x; p1->x = p2->x; p2->x = temp; temp = p1->y; p1->y = p2->y; p2->y = temp; } //将三个顶点按逆时针方向排序 void sortPoints(Point *pts) { if(pts[0].y < pts[1].y) swap(&pts[0],&pts[1]); Point ca = {-pts[2].x + pts[0].x, -pts[2].y + pts[0].y}; Point cb = {-pts[2].x + pts[1].x, -pts[2].y + pts[1].y}; if(ca.x * cb.y - ca.y * cb.x < 0) swap(&pts[1],&pts[2]); } int crossProduct(Point &p1, Point &p2) { return -p1.y*p2.x + p1.x*p2.y; } bool inTriangle(Point *pts, Point &d) { Point ad = {d.x - pts[0].x, d.y - pts[0].y}; Point ac = {pts[2].x - pts[0].x, pts[2].y - pts[0].y}; Point ab = {pts[1].x - pts[0].x, pts[1].y - pts[0].y}; Point bd = {d.x - pts[1].x, d.y - pts[1].y}; Point ba = {pts[0].x - pts[1].x, pts[0].y - pts[1].y}; Point bc = {pts[2].x - pts[1].x, pts[2].y - pts[1].y}; Point cd = {d.x - pts[2].x, d.y - pts[2].y}; Point cb = {pts[1].x - pts[2].x, pts[1].y - pts[2].y}; Point ca = {pts[0].x - pts[2].x, pts[0].y - pts[2].y}; if(crossProduct(ad, ac) > 0 && crossProduct(ad, ab) < 0 && crossProduct(bd, ba) > 0 && crossProduct(bd, bc) < 0 && crossProduct(cd, cb) > 0 && crossProduct(cd, ca) < 0) return true; return false; }