- Home /
Change alpha value to transparent when colliding
Hey guys! I have a little game where my player (has a sprite renderer) gets hit by an enemy and after each hit I want to change his alpha value a little bit until he almost becomes transparent. I saw that it is possible by doing a color lerp or with the DOTween plugin. Sadly I didn't manage to do it. That is what I have now:
private void Fade(float endValue, float fadeDuration, TweenCallback onEnd)
{
if(fadeTween != null)
{
fadeTween.Kill(false);
}
fadeTween = canvasGroup.DOFade(endValue, fadeDuration);
fadeTween.onComplete += onEnd;
}
private void FadeOut(float fadeDuration)
{
Fade(0f, fadeDuration, () =>
{
canvasGroup.interactable = false;
canvasGroup.blocksRaycasts = false;
});
}
Nothing happens to my player. Is something wrong in my code or is there another solution? I would be glad if someone can help me out :)
Answer by alphaa153 · Jan 30 at 02:55 PM
The best way (in my opinion) to fade a sprite is to modify the alpha value of the color. To do this it's incredibly easy you can do it with this line of code:
float fadeSpeed = 0.1f;
transform.GetComponent<SpriteRenderer>().color -= new Color(0, 0, 0, fadeSpeed * Time.deltaTime);
For example in this line it will take 10 seconds for the sprite to fade (the alpha value goes from 0 to 1)
So here is your code:
private void Fade(float speed)
{
transform.GetComponent<SpriteRenderer>().color -= new Color(0, 0, 0, speed * Time.deltaTime);
//Will make the sprite fade smoothly
}
private void FadeOut()
{
Color color = transform.GetComponent<SpriteRenderer>().color;
transform.GetComponent<SpriteRenderer>().color = new Color(color.r, color.g, color.b, 0);
// Will make the sprite dissapear
}
Altough if you want to make your sprite disappear it's better to just disable the sprite renderer
transform.GetComponent<SpriteRenderer>().enabled = false;
If I misunderstood something let me know.