From f986dc197b5e093575bc0b56ee0ded991c228639 Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Tue, 9 May 2023 13:14:14 +0800 Subject: *misc --- .../Physics/PhysicsManager_CollisionDetection.cs | 80 ++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 marching/Assets/Scripts/Physics/PhysicsManager_CollisionDetection.cs (limited to 'marching/Assets/Scripts/Physics/PhysicsManager_CollisionDetection.cs') diff --git a/marching/Assets/Scripts/Physics/PhysicsManager_CollisionDetection.cs b/marching/Assets/Scripts/Physics/PhysicsManager_CollisionDetection.cs new file mode 100644 index 0000000..81625ac --- /dev/null +++ b/marching/Assets/Scripts/Physics/PhysicsManager_CollisionDetection.cs @@ -0,0 +1,80 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public partial class PhysicsManager : Singleton +{ + + /// + /// circle x,y,radius + /// + /// + /// + /// + /// + /// + public static bool CircleVsCircle(Vector2 pos1, float r1, Vector2 pos2, float r2) + { + return (pos1 - pos2).magnitude <= r1 + r2; + } + + public static bool CircleVsCircle(Vector3 c1, Vector3 c2) + { + return (c1.xy() - c2.xy()).magnitude <= c1.z + c2.z; + } + + /// + /// intersectionÊÇr2¶ÔÓÚr1 + /// + /// + /// + /// + /// + public static bool BoxVsBox(Vector4 b1, Vector4 b2, out Vector2 intersection) + { + float b1w = b1.z / 2f, b1h = b1.w / 2f, b2w = b2.z / 2f, b2h = b2.w / 2f; + float distX = b2.x - b1.x; + float distY = b2.y - b1.y; + if(Mathf.Abs(distX) < b1w + b2w && Mathf.Abs(distY) < b1h +b2h) + { + intersection = new Vector2(); + intersection.x = Mathf.Sign(distX) * (b1w + b2w - Mathf.Abs(distX)); + intersection.y = Mathf.Sign(distY) * (b1h + b2h - Mathf.Abs(distY)); + return true; + } + intersection = Vector2.zero; + return false; + } + + public static bool BoxVsCircle(Vector4 box, Vector2 pos, float radius) + { + Vector4 boxScaled = box; + boxScaled.z = box.z + radius * 2; + boxScaled.w = box.w + radius * 2; + if (!IsPointInsideBox(boxScaled, pos)) + return false; + Vector2 v = MathUtils.Abs(pos - box.xy()); + Vector2 u = MathUtils.Max(v - box.zw(), 0); + return Vector2.Dot(u, u) < radius * radius; + } + + /// + /// box x,y,w,h circle x,y,raduis + /// + /// + /// + /// + public static bool BoxVsCircle(Vector4 box, Vector3 circle) + { + return BoxVsCircle(box, circle.xy(), circle.z); + } + + public static bool IsPointInsideBox(Vector4 box, Vector2 point) + { + return point.x >= box.x - box.z / 2f + && point.x <= box.x + box.z / 2f + && point.y >= box.y - box.w / 2f + && point.y <= box.y + box.w / 2f; + } + +} -- cgit v1.1-26-g67d0