判断点是否在三角形内

算法思想:利用向量叉积性质判断点和三角形边的相对位置关系。需要注意的是,在计算叉积之前需要先将三个顶点按顺时针或者逆时针方向排好序。

叉积相关概念和性质参见:

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;
}

转载于:https://www.cnblogs.com/segeon/archive/2012/08/28/2659912.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值