游戏中的数学计算
游戏中的数学计算
判断点是否在圆形区域内
对于一个点 (x,y),它到圆心 (xCenter,yCenter) 的最短距离d_sqr= (x − xCenter)^2 +(y − yCenter)^2,如果d_sqr小于等于半径 radius^2,那么这个点就在圆内(包括边界)。
判断点是否在正方形区域内
public static bool IsPointInRotatedSquareWithQuickReject(float pointX, float pointY,float squareCenterX, float squareCenterY,float squareSize, float rotationRadians){// 平移坐标到正方形中心float dx = pointX - squareCenterX;float dy = pointY - squareCenterY;// 1. 快速拒绝:外接圆检测 外接圆半径 = (size/2) * √2// √2 ≈ 1.41421356237 → 0.5*1.4142 ≈ 0.7071float circumcircleRadius = squareSize * 0.70710678118f; float distanceSqr = dx * dx + dy * dy;// 如果距离平方 > 外接圆半径平方,直接返回falseif (distanceSqr > circumcircleRadius * circumcircleRadius){return false;}// 2. 精确检测:坐标变换 + 边界判断float cosTheta = MathF.Cos(rotationRadians);float sinTheta = MathF.Sin(rotationRadians);// 将点坐标反向旋转到正方形局部坐标系float localX = dx * cosTheta + dy * sinTheta;float localY = -dx * sinTheta + dy * cosTheta;// 判断局部坐标是否在轴对齐正方形内float halfSize = squareSize / 2;return Math.Abs(localX) <= halfSize && Math.Abs(localY) <= halfSize;}
判断圆形区域与矩形区域 相交
public bool CheckCircleSquareIntersect(LVector2 circleCenter, LFloat circleRadius, LVector2 squareCenter, LFloat squareSize)
{// 计算圆心在正方形坐标系中的偏移量LFloat dx = circleCenter.x - squareCenter.x;LFloat dy = circleCenter.y - squareCenter.y;// 正方形的半边长LFloat halfSize = squareSize / 2;// 约束到正方形边界内的最近点// 即在正方形内 找一个距离圆 最近的点LFloat closestX = LMath.Clamp(dx, -halfSize, halfSize);LFloat closestY = LMath.Clamp(dy, -halfSize, halfSize);// 计算平方距离LFloat distanceSqr = (dx - closestX) * (dx - closestX) + (dy - closestY) * (dy - closestY);// 判断是否相交var checkCircleSquareIntersect = distanceSqr <= (circleRadius * circleRadius);if (checkCircleSquareIntersect){Log.Error($"is intersect distance is : {distanceSqr}, r^2 is {circleRadius * circleRadius}");}return checkCircleSquareIntersect;
}