- Home /
3D Text Size Relative To Screen?
Hello.
I recently added some 3D text to my scene to follow the top of the player. This was done so the Player's name wouldn't appear when he was behind a building.
I got that to successfully work, but the only problem I'm having now that I moved it into 3D space, is that the text doesn't keep the same size relative to the screen size. The further you go away, the the harder it is to notice the player's name. Anyone know how to keep the size consistent relative to the screen?
Thank you
Adam
Answer by Ivan-Carmosino · Dec 21, 2016 at 08:20 AM
You could set the scale of the textGameObject in according to the distance from the camera in this way:
using UnityEngine;
public class ScaleMeshText : MonoBehaviour {
[Tooltip("Distance of the MeshObject with no calculateScale")]
public float distance = 7.0f;
Vector3 startScale;
void Start () {
startScale = transform.localScale;
}
void Update () {
scale();
}
void scale()
{
float dist = Vector3.Distance(Camera.main.transform.position, transform.position);
Vector3 newScale = startScale * (dist / distance);
transform.localScale = newScale;
}
}
Answer by drawcode · Sep 25, 2012 at 09:49 PM
You could set the scale of the object according to the distance from the camera. You will have to adjust the values/settings but basically just use Vector3.Distance on the camera transform and the 3d text transform.
public class Example : MonoBehaviour {
public Transform cameraTransform;
void Example() {
if (other) {
float dist = Vector3.Distance(cameraTransform.position, transform.position);
print("Distance to other: " + dist);
Vector3 newScale = transform.localScale;
// adjust local scale based on distance
transform.localScale = newScale;
}
}
}
You can also combine this with http://wiki.unity3d.com/index.php?title=CameraFacingBillboard for other types not just 3d text.
This doesn't do anything - you're simply applying the current scale ... to the current scale, the 'dist' is never used.
Answer by Eric5h5 · Sep 26, 2012 at 01:03 AM
Use a GUIText object instead of 3D text. (For example.)
Answer by ridlr · Jun 12, 2020 at 08:34 PM
Obviously this is an old thread, but just thought I would help anybody else looking for an answer. The first thing you must do is pick a default font size and relative default distance, like so:
float defaultDistance = 4f;
float defaultSize = 40f;
Then use something like this to resize it:
float dist = Vector3.Distance(playerCamera.position, transform.position);
textMesh.fontSize = Mathf.RoundToInt(defaultSize * Mathf.Sqrt(dist / defaultDistance));
The square root is key here, because otherwise the text will scale disproportionately to the camera's distance.
Your answer
Follow this Question
Related Questions
Changing a GUILabel text SIZE 3 Answers
Unity 4.6.1 Font Size Cannot Go Over 25 6 Answers
Relate font size to screen size in GUISkin 2 Answers
how to scale and position guiText in android 1 Answer
Changing the size of a GUI label 1 Answer