向量法判断点是否在多边形内部
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/3fb06c63549443bbbad1f6fe817ceb93.jpeg#pic_center)
方法
- 如图所示(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);
std::cout << "intersect_adjust result : " << intersect_adjust(polygon_test, test_point) << std::endl;
return 0;
}