- Home /
Question by
Pengawk · Jul 27, 2016 at 07:11 PM ·
c#color changeramp
Ramping Alpha Based on Distance
So, I have the following code in my project:
void RampAlpha(float dt)
{
Vector3 aPosition = (aEnemy.transform.position - aPlayer.transform.position).normalized * aEnemy.AggroRange + aPlayer.transform.position;
Color aColor = new Color(1, 1, 1, 0);
aColor.a = Mathf.Clamp(aPosition.magnitude / aEnemy.transform.position.magnitude, 0.0f, 1.0f);
if (aColor.a < 0.70f)
aColor.a = 0;
aEnemy.GetComponentInChildren<SpriteRenderer>().color = Color.Lerp(aEnemy.GetComponentInChildren<SpriteRenderer>().color, aColor, dt);
}
And what I want it to do is ramp alpha so that a sprite becomes more visible as it gets closer to the player, but it's not doing that 100% of the time. Occasionally, if the player shares an axis (same x or same z), the sprite is visible. How can I prevent this?
Comment
Best Answer
Answer by Jessespike · Jul 27, 2016 at 09:01 PM
You'll have to make adjustments to make the code work with yours, there should be enough here for you to resolve the problem.
public float minRange = 10f;
public float maxRange = 100f;
// Update is called once per frame
void Update () {
// calculate lerp amount (alpha) by the distance and the provided ranges
float distance = Vector3.Distance(transform.position, Camera.main.transform.position);
float lerpAmt = 1.0f - Mathf.Clamp01((distance - minRange) / (maxRange - minRange));
// update material's alpha
Renderer renderer = transform.GetComponent<Renderer>();
Color color = renderer.material.color;
color.a = lerpAmt;
renderer.material.color = color;
// output current values
Debug.Log(string.Format("Distance = {0} \t(range = {1} to {2})\t LerpAmt = {3}",
distance, minRange, maxRange, lerpAmt));
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Changing material color from dictionary (C#) 0 Answers
How can I loop through all colours in code? 1 Answer
How to create shared color channels 1 Answer