正六边形:判断点是否在正六边形内

 前文 正六边形:平铺中函数

//根据坐标计算网格信息
Vec2 HelloWorld::getGridByPos(const Vec2& pos)
{
	int girdX = pos.x/ (1.5 * sideLen)+0.5;
	int girdY = 0;
	if (girdX % 2 == 0)
	{
		girdY = pos.y / (sideLen * sqrt3) + 0.5;
	}
	else
	{
		girdY = pos.y / (sideLen * sqrt3) + 1;
	}
	return Vec2(girdX, girdY);
}

逻辑存在BUG,处于边界时计算有误,需要判断点是否在正六边形内进行纠偏处理。

如何判断点是否在正六边形内?

把正六边形分解,将问题转换为,点是否在矩形IGDJ或三角形GCD内;

 

正六边形:判断点是否在正六边形内

设dx,dy分别为点到正六边形中心点的差值【>=0】,

若点在矩形内,则dx必然在IG区间【dx<1】且dy在IJ区间【dy<1.73】

若点在三角形内,则dx必然在GC区间【1<dx<2】且dy在DC线的下方【以G点为原点,DC线的坐标关系描述为y= -1.73x+1.73】

代码实现如下:

const int cubeSideLen = 2;
const int halfSideLen = cubeSideLen * 0.5;
const double mathSqrt3 = 1.732051;
const double cubeSideLen_X_mathSqrt3 = cubeSideLen * mathSqrt3;

class Grid
{
public:
	Grid() {}
	Grid(int x, int y, int z = 0) {
		this->x = x;
		this->y = y;
		this->z = z;
	}

	int x = 0;
	int y = 0;
	int z = 0;
	
	//六边形中心坐标
	double posX = 0;
	double posY = 0;

	//指定坐标是否在六边形内
	bool posInGrid(const double &posX, const int& posY) 
	{
		double dx = std::abs(this->posX - posX);
		double dy = std::abs(this->posY - posY);
		if (dx <= halfSideLen)
		{
			return dy <= halfSideLen * mathSqrt3;
		}
		else
		{
			int maxY = -mathSqrt3 * (dx - halfSideLen) + halfSideLen * mathSqrt3;
			return dy < maxY;
		}
	}
};

 

上一篇:2021-05-06


下一篇:【牛客网】岛屿数量