碰撞检测小工具

enum class CollDir {
	None,
	Top,
	Bottom,
	Left,
	Right
};

CollDir DetectCollisionDirection(const Entity& e1, const Entity& e2) {
	// 确定person和wall的边界
	int personLeft = e1.x;
	int personRight = e1.x + e1.width;
	int personTop = e1.y;
	int personBottom = e1.y + e1.height;

	int wallLeft = e2.x;
	int wallRight = e2.x + e2.width;
	int wallTop = e2.y;
	int wallBottom = e2.y + e2.height;

	// 检查是否没有碰撞
	if (personRight < wallLeft || personLeft > wallRight || personBottom < wallTop || personTop > wallBottom) {
		return CollDir::None;
	}

	// 计算碰撞的深度
	int bottomCollision = personBottom - wallTop;
	int topCollision = wallBottom - personTop;
	int leftCollision = wallRight - personLeft;
	int rightCollision = personRight - wallLeft;

	// 找到最小碰撞深度
	int minCollision = std::min({ bottomCollision, topCollision, leftCollision, rightCollision });

	// 根据最小碰撞深度判断碰撞方向
	if (minCollision == bottomCollision) {
		return CollDir::Top;
	}
	else if (minCollision == topCollision) {
		return CollDir::Bottom;
	}
	else if (minCollision == leftCollision) {
		return CollDir::Right;
	}
	else if (minCollision == rightCollision) {
		return CollDir::Left;
	}

	return CollDir::None;
}

你可能感兴趣的:(算法)