# How to channel 2d sprite alpha depending on distance

Hello

I have a simple sprite to where it starts at one point with alpha color set to 100. As it reaches its halfway mark from its 2nd position the sprite alpha should gradually fade to 0 then increases back to 100 as it’s reaching its 2nd position.

### How would I go about doing this?

Hello @GameDevH2O,

I think this should do (I added comments to explain, you can tweak it to understand it better):

``````    public Transform spot1;
public Transform spot2;
public SpriteRenderer spriteRenderer;

private void Update() {
// Calculate the distances to each spot
float distanceToSpot1 = Vector3.Distance(this.transform.position, this.spot1.position);
float distanceToSpot2 = Vector3.Distance(this.transform.position, this.spot2.position);

// Calculate the total distance between the two spots
float totalDistance = distanceToSpot1 + distanceToSpot2;

// Calculate the normalized distance from spot1 to the sprite
float normalizedDistanceToSpot1 = distanceToSpot1 / totalDistance;

// Interpolate alpha between 0 and 1 based on the normalized distance
float alpha = Mathf.SmoothStep(0f, 1f, Mathf.Abs(normalizedDistanceToSpot1 - 0.5f) * 2f);

// Apply the alpha value to the sprite renderer
this.SetAlpha(alpha);
}

private void SetAlpha(float alpha) {
this.spriteRenderer.color = new Color(this.spriteRenderer.color.r, this.spriteRenderer.color.g, this.spriteRenderer.color.b, alpha);
}

}
``````

You can change the alpha of a sprite by changing the color used in the sprite renderer to a white color with different alpha.

For example, here is a function which will change the alpha to a value you specify. It is up to you to define how and when you would call this function. It sounds like you will need something else comparing the distance of the object to some other positions in the world.

``````[SerializeField] private SpriteRenderer mySprite;

// 0.0f = transparent
// 1.0f = opaque
private void SetAlpha(float alpha)
{
mySprite.color = new Color(1, 1, 1, alpha);
}
``````