平面几何——判断点是否在多边形内部

在判断点是否在平面上多边形内的方法,本文使用了经典的射线法,也可以叫奇偶规则。使用了一个水平射线与多边形的交点数来确定点是否在多边形内部。

  1. 水平射线交点的数目
    • 当你从点出发发射一条水平射线(水平射线与多边形边交点的数目),射线穿过多边形边的数量决定了该点是否在多边形内部。
    • 具体来说,如果射线穿过多边形的边界一次或多次,我们可以判断点的位置:
      • 奇数次交点:如果射线与多边形的边交点数是奇数,则点位于多边形内部。原因是每次穿越边界意味着点在多边形的外部进入内部,或从内部进入外部。如果交点数是奇数,则表示从外部进入内部的次数比从内部退出外部的次数多一次,因此点在多边形内部。
      • 偶数次交点:如果射线与多边形的边交点数是偶数,则点位于多边形外部。偶数次交点表示点在边界的进出次数相等,从而回到原来的位置,即点在多边形外部。

关键代码:

float xIntersection = (point.y - low.y) / (high.y - low.y) * (high.x - low.x) + low.x;

解释:这个公式计算的是水平射线与多边形边的交点在 x 轴上的位置,(point.y - low.y) / (high.y - low.y)计算了点的 y 坐标相对于边的 y 坐标范围的相对位置,* (high.x - low.x),将前面的比例值乘以这个宽度,得到点的 y 坐标对应于边上 x 坐标的相对位置,+ low.x,将之前计算得到的相对 x 坐标加上 low.x,得到实际的交点 x 坐标。

完整代码实现如下:

#include <vector>
#include <algorithm>
#include <iostream>

struct Vector2 {
	float x, y;

	// 添加构造函数、拷贝构造函数和赋值运算符
	Vector2() : x(0), y(0) {}
	Vector2(float x, float y) : x(x), y(y) {}
	Vector2(const Vector2&) = default;
	Vector2& operator=(const Vector2&) = default;

	// 定义比较操作符
	bool operator==(const Vector2& other) const {
		return x == other.x && y == other.y;
	}

	bool operator!=(const Vector2& other) const {
		return !(*this == other);
	}
};

bool isVectorInPolygon(const Vector2& point, const std::vector<Vector2>& polygon) {
	int count = 0;
	size_t numVertices = polygon.size();

	for (size_t i = 0; i < numVertices; ++i) {
		const Vector2& start = polygon[i];
		const Vector2& end = polygon[(i + 1) % numVertices];

		// 确保 start 是 y 坐标较小的点
		Vector2 low = start;
		Vector2 high = end;
		if (low.y > high.y) std::swap(low, high);

		// 检查点是否在 y 坐标范围内
		if (point.y >= low.y && point.y <= high.y) {

			if (high.y == low.y) {
				// 如果是水平线段,且点的 y 坐标等于线段的 y 坐标,则跳过
				if (point.y == low.y) continue;
			} else {
				float xIntersection = (point.y - low.y) / (high.y - low.y) * (high.x - low.x) + low.x;
				if (xIntersection <= point.x) ++count;
			}
	}
	// 点在多边形内部的条件是交点数为奇数
	return count % 2 == 1;
}

int main() {
	Vector2 point = { 0.5f, 0.5f }; // 点坐标
	std::vector<Vector2> polygon = {
		{0.0f, 0.0f},
		{1.0f, 0.0f},
		{1.0f, 1.0f},
	    {0.5f,1.5f},
		{0.0f, 1.0f}
	}; // 多边形顶点

	bool result = isVectorInPolygon(point, polygon);
	std::cout << "Is vector in polygon: " << (result ? "Yes" : "No") << std::endl;
	std::cout << "Press any key to continue...";
	system("pause");  // 等待用户按任意键


	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值