Testing ideas
The first thing to do is to convert box to AABB and then determine if the center is in box, using the SAT
If the center is inside the box, it must intersect,
If it is not within the center of the circle, there are four cases, intersecting the vertices, intersecting with the faces, and intersecting the polygons, where the determination is also determined by the SAT.
In two dimensions, if the center is not inside the box, there are a couple of cases
Just compare the length of the red line and the radius of the circle.
Code
public static bool Intersectspherebox (Sphere Sphere, Box box) {Vector3 Delta = Sphere.center-box.cen ter matrix4x4 Boxrotmatrix = Matrix4x4.trs (Vector3.zero, box.rotation, Vector3.one); Vector3 Drot = boxRotMatrix.inverse.MultiplyVector (delta); bool outside = FALSE; if (Drot.x <-box.extents.x) {outside = true; Drot.x =-box.extents.x; } else if (Drot.x > box.extents.x) {outside = true; Drot.x = box.extents.x; } if (Drot.y <-box.extents.y) {outside = true; Drot.y =-box.extents.y; } else if (Drot.y > Box.extents.y) {outside = true; Drot.y = Box.extents.y; } if (Drot.z <-box.extents.z) {outside = true; Drot.z =-Box.extents.z; } else if (Drot.z > box.extents.z) {outside = true; Drot.z = box.extents.z; if (outside)//if clipping was did, Sphere Center is outside of box. {Vector3 Clippeddelta = Boxrotmatrix.multiplyvector (Drot); Get clipped Delta back on world coords. Vector3 Clippedvec = Delta-clippeddelta; What we clipped away. float lensquared = clippedvec.sqrmagnitude; float radius = Sphere.radius; if (lensquared > Radius * radius)//pt:objects is defined as closed, so we return ' true ' in case of equality return false; disjoint} return true; }
Test code
public class Sphereboxtester:monobehaviour {public Gameobject sphere; public Gameobject Box; Box _box; Sphere _sphere; Use the this for initialization void Start () {_box = new box (); _sphere = new Sphere (); }//update is called once per frame void Update () {_box.center = box.transform.position; _box.rotation = box.transform.rotation; _box.extents = 0.5f * Box.transform.localScale; _sphere.center = sphere.transform.position; _sphere.radius = 0.5f * sphere.transform.localscale.x; if (Nintersecttests.intersectspherebox (_sphere, _box)) {sphere. Getcomponent<meshrenderer> (). Materials[0]. SetColor ("_color", New Color (1, 0, 0)); } else {sphere. Getcomponent<meshrenderer> (). Materials[0]. SetColor ("_color", New Color (1, 1, 1)); } }}
Run results
Sphere-box Detection of collision detection