/// <summary> /// OBB之间是否接触 /// </summary> public static bool IsContacted(OBB obb1, OBB obb2) { bool rect1Torect2IsContact = false; bool rect2Torect1IsContact = false; rect1Torect2IsContact = IsContact(obb1, obb2); rect2Torect1IsContact = IsContact(obb2, obb1); if (rect1Torect2IsContact == true && rect2Torect1IsContact == true) { return true; } return false; }
/// <summary> /// 构造OBB,OBB必须比AABB小! /// </summary> public void StructureOBB(Vector2 dir, float width, float height) { Obb = new OBB(new Vector2(X, Y), dir, width, height); }
// 使用一个矩形的4条边作候选分离轴 static bool IsContact(OBB obb1, OBB obb2) { bool isInLine1 = false; bool isInLine2 = false; bool isInLine3 = false; bool isInLine4 = false; Vector2 line1p1 = obb1.GetPoints()[0]; Vector2 line1p2 = obb1.GetPoints()[1]; isInLine1 = RectAllPointIsInLine(line1p1, line1p2, obb2); Vector2 line2p1 = obb1.GetPoints()[1]; Vector2 line2p2 = obb1.GetPoints()[2]; isInLine2 = RectAllPointIsInLine(line2p1, line2p2, obb2); Vector2 line3p1 = obb1.GetPoints()[2]; Vector2 line3p2 = obb1.GetPoints()[3]; isInLine3 = RectAllPointIsInLine(line3p1, line3p2, obb2); Vector2 line4p1 = obb1.GetPoints()[3]; Vector2 line4p2 = obb1.GetPoints()[0]; isInLine4 = RectAllPointIsInLine(line4p1, line4p2, obb2); if (isInLine1 == true && isInLine2 == true && isInLine3 == true && isInLine4 == true) {//全部边都满足 投影相交 return true; } return false; }
//判断4个投影点有没有与指定线段相交 static bool RectAllPointIsInLine(Vector2 linep1, Vector2 linep2, OBB obb2) { //获取rect4的4个投影点 Vector2 pointPro1 = GetProjectionPoint(linep1, linep2, obb2.GetPoints()[0]); Vector2 pointPro2 = GetProjectionPoint(linep1, linep2, obb2.GetPoints()[1]); Vector2 pointPro3 = GetProjectionPoint(linep1, linep2, obb2.GetPoints()[2]); Vector2 pointPro4 = GetProjectionPoint(linep1, linep2, obb2.GetPoints()[3]); //根据line 的斜率选择映射到X/Y轴来计算 float k = (linep2.Y - linep1.Y) / (linep2.X - linep1.X); #region …… if (k > -0.25f && k <= 0.25) { //映射到X轴 List<float> rectPX = new List<float>(); rectPX.Add(pointPro1.X); rectPX.Add(pointPro2.X); rectPX.Add(pointPro3.X); rectPX.Add(pointPro4.X); return PointIsInLineSegment(linep1.X, linep2.X, rectPX); } else { //映射到Y轴 List<float> rectPY = new List<float>(); rectPY.Add(pointPro1.Y); rectPY.Add(pointPro2.Y); rectPY.Add(pointPro3.Y); rectPY.Add(pointPro4.Y); return PointIsInLineSegment(linep1.Y, linep2.Y, rectPY); } #endregion }
/// <summary> /// 构造OBB,OBB必须比AABB小! /// </summary> public void StructureOBB(Vector2 dir, float width, float height) { Obb = new OBB(new Vector2(X,Y), dir, width, height); }