- Home /
Collider closestPointOnBounds returning point that is not touching the collider
ClosestPointOnBounds is returning a point that is away from the collider and not touching the collider. See the laser below that is not touching the white box. This happens whenever I have a box at an angle. as shown below.
Here is the code in the laser object:
Vector3 m_targetPos = m_target.collider.ClosestPointOnBounds(transform.position);
LineRenderer m_line.SetPosition (0, transform.position);
m_line.SetPosition (1, m_targetPos);
Answer by CHPedersen · May 07, 2013 at 02:16 PM
This happens because the collider's bounding volume is axis-aligned. Unfortunately, the collider doesn't come with a built-in way to solve this.
There is another question here that appears to tackle a similar issue. In this question, Duck shares an algorithm that calculates the closest vertex on the mesh. This might still not suit your purpose, however, since the box is a very simple mesh, all of whose vertices are at the corners. So the laser would only target the corners. But maybe it will work for you later in your project, if your models are more complex? (I'm assuming you're using the box as a temporary model during development)
In any case, I don't know exactly what kind of behavior you want this laser to exhibit, so bear with me... But I think you're going about this the wrong way to begin with. Usually with lasers, people do raycasts from the laser's position in some firing direction, and then evaluate the ray cast against the colliders. The returned RayCastHit object has the exact point. Maybe this is actually more like what you need?
Thanks for the explanation. Collider.RayCast works perfectly.
P.S: I used collider of the cube because I am targeting only the cube. Thanks for answering my question so quickly.
Super. If you feel it helped, it would be great if you could mark the answer accepted, please. :)
for someone that may has this problem in 2d: ins$$anonymous$$d of getting the bounds of the renderer use the bounds of the renderers sprite. Those are NOT axis-aligned! Still, great to see that some people were dealing with the same problems that I had lately :D
Answer by demonpants · May 07, 2014 at 06:11 PM
What I'm doing is using Unity's closestPointOnBounds to get a direction from my target to the collider, then doing a raycast from there to get the specific point. This works well enough for my purposes, but in some cases will yield no point because the bounds may be outside the edges.
this is a pretty good idea! Because I need the exact magnitude between the two objects. Now I just need to find a way of fixing the issue you mentioned. thx!