0
\$\begingroup\$

I have a bunch of TextMeshPro labels in a scene at various x,y,z positions and I would like to detect when labels overlap from the camera's perspective so I can keep the labels from stacking. The labels on the left & right of the image are visually overlapping but physically they have different z indices so a classic 3d collision won't work.

tmp labels across view

How can I detect "2d collisions" for 3d gameobjects?

extra

My camera moves AROUND the sphere of labels otherwise I could probably get away with putting all the labels on the same z-index;

** EDIT **

current TEMPORARY solution

3d collider in the label prefab with a very exaggerated z-index

\$\endgroup\$
2

1 Answer 1

0
\$\begingroup\$

You can use Physics.RaycastAll on screen-points of the corners of the last text object you created. If there is more than one hit on any of the corners it means there is another object behind. Then, you can relocate your latest object and check again.

Roughly it should go like this. You need to find a way to calculate corner positions in world space (i.e. GetCornerWorldPositions(myText)):

List<Vector3> cornerWorldPositions = GetCornerWorldPositions(myText);

foreach (Vector3 cornerWorldPosition in cornerWorldPositions)
{
    Vector3 cornerScreenPosition = Camera.main.WorldToScreenPoint(cornerWorldPosition);
    Ray ray = Camera.main.ScreenPointToRay(cornerScreenPosition);
    RaycastHit[] hits = Physics.RaycastAll(ray, 100f);

    if (hits.length > 1) { // There is an object behind. }
}

You may need to add a safety that shrinks the corner coordinates towards the center to prevent approximation errors during raycasting.

Also, use a tag to prevent raycasting from interfering with objects other than texts.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .