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?

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} 	(range = {1} to {2})	 LerpAmt = {3}", 
	                        distance, minRange, maxRange, lerpAmt));
}