I’ve been trying to find a way to get the closest Edge/Vertex position of a 3D BoxCollider from a given Vector3 Position.
In this case I hit a 3D BoxCollider with a Raycast and get the Point where it hit. Now I want to get the closest Edge or Vertex of that BoxCollider to the Point of the Raycast;
How can I do this?
Thank you in advance!
The general approach is always the same. You would first transform your position into the local space of the collider by using
transform.InverseTransformPoint(). Once the point is in local space it’s just a matter of determining / projecting your point onto the right element. You said edge and vertex. Those are conceptionally quite different things. So it’s not quite clear what you’re looking for exactly. Keep in mind that a BoxCollider has a center “offset” and a “size” besides the transform manipulations.
A default cube has a size of 1,1,1 and an offset of 0,0,0. Note that the size is the total size, not the extent. If you just scaled a default cube with the transform, this will already be handled by the inverse transform. However if your collider has a changed size / center you have to keep that in mind as well. In essence you just have to add the center to the local position of your point of interest and also divide each component by the component of the size to get to the same basis. The 8 corners are just ± 0.5
If you want to find the closest vertex / corner of the box, all you have to do is analyse the sign of the 3 components. So if x is positive, you know the closest vertex is one of the 4 corners on the right side, otherwise one of the 4 corners of the left side. Likewise if y is positive it’s one of the two upper vertices, otherwise the two lower vertices. Finally the z sign tells you if it’s the front or back vertex.
Determining the edges is a bit more complicated sinde a cube has 12 edges. Here it’s necessary to determine which component is greater. While a specific corner has a single vertex position, an edge consists of two vertices. So the “selection” of an edge is also more complicated. Also edges are actually orientated. So it depends on your actual needs what you should do.