- Home /
How to change text alpha with distance?
Hello! Looks simple, but there is complication. I have a canvas over object with animated UI text - animation already changes its alpha so text becomes transparent over time. And ALSO I need it to slowly vanish when player is too far. What is the best way to get it done?
Answer by Stratosome · Jul 16, 2018 at 09:50 AM
Well, one idea you could try is to have a "max distance" that the player can walk from the object until the canvas is fully invisible. Get the current distance from the player and do something like (currentDist/maxDist) to get a percentage. This can be your distanceAlpha. Now you have two potential alpha values for the canvas (distanceAlpha and timerAlpha). Pick whichever one is the greatest (or least depending on how you do it) and apply only that alpha to the canvas.
Although I guess I assumed that when you said animated UI text, it was perhaps a coroutine handling that. If it is Unity's animation system ins$$anonymous$$d, it may be a bit different.
@Stratosome and @tormentoarmagedoom, thanks for your answers! Yes, its animation system. Its like, you know, damage number, that fly away from enemy after hit, and vanish in the air. I achived that with animator. And now I need it to be visible for player only in close distance.
Ah, gotchya. Hrmm, I'm not quite sure the best way to get the animation's alpha and the distance alpha to interact nicely when using the animator. Personally, I'd just use a coroutine ins$$anonymous$$d of the animator to put a little timer on the text that pops up. You'd have more control over it too in code.
private IEnumerator TextAlphaTimer(float duration) {
float elapsedTime = 0;
while (elapsedTime < duration) {
float percentageComplete = (elapsedTime / duration);
// Update text alpha here
// ...
elapsedTime += Time.deltaTime;
yield return null;
}
// Timer is complete
// ...
}
Answer by tormentoarmagedoom · Jul 16, 2018 at 09:46 AM
Good day.
You need to do it by code, not by animation.
You just need to use
float distance == Vector3.Distance(position1, position2);
and then change the color depending ont he distance value by:
float TheAlphaValue = (Here you must calculate what alfa you want related to distance value)
Text.color = new Color (text.color.r, text.color.g, text.color.b, TheAlphaValue);
Try it, look for tutorials to understand everything, and try try try!
Bye!
Your answer
Follow this Question
Related Questions
How can i pay a animation again and agan? 1 Answer
Animating Transitions for GUI Results 0 Answers
Can the animation editor create local rotational data? 3 Answers
Adding animation clips via script 2 Answers
UI text animation 0 Answers