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.

[10792-collider+not+hitting.png|10792]

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);

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 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?