- Home /
Collider around GUI text
I'm making a simlpe word bazed game, and for that I'd like to have a collider around the words I'm displaying (I use GUItext for that).
I tried using a box collider, but I can't seem to find a good way to automaticly set size of the collider to match size of the word.
Code I've tried so far:
void setCollider()
{
BoxCollider boxCollider = (BoxCollider) gameObject.AddComponent (typeof (BoxCollider));
boxCollider.isTrigger = true;
boxX = 0.1f * (guiText.text.Length - 1);
boxCollider.size = new Vector3(boxX, boxY, 1);
}
This function is called from the start() function. It doesn't give consistent results.
Answer by robertbu · May 03, 2014 at 11:47 PM
You can use GUIText.GetScreenRect() to get the Screen/pixel size of the text. You then need to convert that size into world space. For a perspective camera, you'll need to pick a distance in front of the camera since world size and world coordinates vary based on the distance from the camera. For an Orthographic camera, you can use the Orthographic.size to directly calculate the world size.
@robertbu
I now have this code:
void setCollider()
{
Rect box = this.guiText.GetScreenRect ();
BoxCollider boxCollider = (BoxCollider) gameObject.AddComponent (typeof (BoxCollider));
boxCollider.isTrigger = true;
boxX = box.width;
boxY = box.height;
//Debug.Log ("boxX = " + boxX + "boxY = " + boxY);
boxCollider.size = new Vector3(boxX, boxY, 1);
}
But the collider is way to big. I assume that is what you mean by "convert that size into world space", but how do I do that?
I'm using ortographic camera.
Your answer
Follow this Question
Related Questions
Read txt file into a game 1 Answer
I am trying to have a ball roll on a line that was drawn from a Line Renderer 1 Answer
Box Colliders of imported OBJ not centered on OBJ, How would i center it? 2 Answers
why isn't my OnTriggerEnter2D() function working? 14 Answers
Note Pad not flipping back 1 Answer