向量法判断点是否在多边形内部

向量法判断点是否在多边形内部

在这里插入图片描述

方法

  • 如图所示(1),当p点在多边形内部时候相邻向量叉乘后的方向是一致的,如(1)图中AP×BP、BP×CP、CP×DP、DP×EP、EP×AP的方向一致。
  • 如图所示(2),当p在多边形外部时候AP×BP与DP×EP的方向不一致

代码

// 使用向量法判断点是否在多边型内部

#include <iostream>
#include <vector>
#include <math.h>


using namespace std;


// 定义点
struct Point2d{
    double x;
    double y;
    // 构造
    Point2d(double _x, double _y):x(_x), y(_y){}
    // 定义减法
    Point2d operator-(Point2d _point){
        return Point2d(this->x - _point.x, this->y - _point.y);
    }
    // 定义加法
    Point2d operator+(Point2d _point){
        return Point2d(this->x + _point.x, this->y + _point.y);
    }
    // 定义除法
    Point2d operator/(double _num){
        return Point2d(this->x / _num, this->y / _num);
    }
    // 定义乘法
    Point2d operator*(double _num){
        return Point2d(this->x * _num, this->y * _num);
    }
    // 定义归一化
    Point2d norm(void){
        double mo = sqrt(x * x + y * y);
        return Point2d(x / mo, y / mo);
    }
};
// 定义叉乘
double cross_product(Point2d p1, Point2d p2){
    return p1.x*p2.y - p1.y*p2.x;
}

// 判断
bool intersect_adjust(vector<Point2d> _polygon, Point2d _point){
    // 顺序一致性判断
    _polygon.push_back(_polygon[0]);
    int z = 0;
    int f = 0;
    for(int i = 0; i < _polygon.size()-1; ++i){
        Point2d pa = _polygon[i] - _point;
        Point2d pb = _polygon[i+1] - _point;
        double cross = cross_product(pa, pb);
        if(cross > 0) z += 1;
        else          f += 1;
        if(z > 0 && f > 0) return false;
    }
    return true;
}

int main(){

    //- 相交测试案例
    vector<Point2d> polygon_test;
    polygon_test.push_back(Point2d(0, 0));
    polygon_test.push_back(Point2d(0, 2));
    polygon_test.push_back(Point2d(2, 2));
    polygon_test.push_back(Point2d(2, 0));
    // Point2d test_point(-0.5,1);// result = 0
    Point2d test_point(0.5,1);// result = 1
    std::cout << "intersect_adjust result : " << intersect_adjust(polygon_test, test_point) << std::endl;

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值