- Home /
Fitting a box collider to 3D text perfectly
Hello,
This question has been posed numerous times in various contexts, but I do not know that a solution has ever been found. I have not encountered one.
I have a menu with 3D text, and I have a box collider of nominal dimensions to detect mouse events (hover and click). So far, so good, except that I would like to size my box colliders according to the size of the text, not nominally. The text itself comprises a mesh, and the most obvious solution would be to read the size of the text from the top left vertex to bottom right vertex, then resize the box collider accordingly. However, I cannot find a way to do this.
Does anybody know how? I am using C#.
Thank you in advance,
Peter
Answer by MikeNewall · Apr 17, 2014 at 02:34 AM
Try this. I'm lazy so I just put the code in OnDrawGizmos.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class ResizeCollider : MonoBehaviour{
public float paddingX;
public float paddingY;
void OnDrawGizmos(){
BoxCollider col = (BoxCollider)collider;
col.center = new Vector3(renderer.bounds.extents.x, renderer.bounds.extents.y - renderer.bounds.size.y, transform.position.z);
col.size = new Vector3(renderer.bounds.size.x + paddingX, renderer.bounds.size.y + paddingY, 1);
}
}
Thank you for your solution, $$anonymous$$ike.
After a few small modifications, your solution worked perfectly. Line 11 threw a casting error, so I replaced that line and RequireComponent with an AddComponent statement. I also altered the calculations slightly to account for my Text $$anonymous$$esh anchor's being at middle centre. In the end, my code read:
void SizeCollider()
{
BoxCollider boxCollider = (BoxCollider) gameObject.AddComponent (typeof (BoxCollider));
boxCollider.center = new Vector3 (renderer.bounds.extents.x - renderer.bounds.size.x / 2, renderer.bounds.extents.y - renderer.bounds.size.y / 2, transform.position.z);
boxCollider.size = new Vector3 (renderer.bounds.size.x + TEXT_PADDING_X, renderer.bounds.size.y + TEXT_PADDING_Y, 1);
}
Interestingly, the bounds property automatically includes the space between letters, and the space below and above the line which would accommodate hanging letters (g, j, y) and accented capitals (for example, Á) even if they are not present. The latter makes sense in this context because I want my colliders to be of equal height, regardless of the letters that the text includes.
Thanks for the updated code. Didn't have a chance to test it properly. Can you accept the answer so other people can see the solution? :)