Sprite blinking effect when player hit
I have a player object and I have attached a sprite to it. I want to create the following effect:
When my player gets hit by an enemy, I want the sprite to blink for a short period of time, like in old arcade games (ex Sonic the Hedgehog).
How can I achieve this effect for my sprite?
Thanks in advance!
Answer by Zoogyburger · Jan 29, 2016 at 01:02 AM
You need to add an animation on your player
In the animation window click Add Property and in the Sprite Renderer click on Enabled
Add a lot of your character frames in the animation and uncheck the box on the sprite renderer on every other frame
Make a script to have this animation play every time the player is hit
Answer by _yash_kaushik_ · Jul 06, 2017 at 01:02 PM
@parisk85 Here is the coding method if someone does not like the animation one :- (in this you will enable and disable the SpriteRenderer component at regular time intervals
create two timers :- (just copy paste them in your code :)) //Sprite blinking effect
public float spriteBlinkingTimer = 0.0f;
public float spriteBlinkingMiniDuration = 0.1f;
public float spriteBlinkingTotalTimer = 0.0f;
public float spriteBlinkingTotalDuration = 1.0f;
public bool startBlinking = false;
void Update()
{
if(startBlinking == true)
{
StartBlinkingEffect();
}
}
void OnTriggerEnter2D(Collider2D col)
{
if(something has entered :) ) //change according to your game
{
startBlinking = true;
}
}
private void SpriteBlinkingEffect()
{
spriteBlinkingTotalTimer += Time.deltaTime;
if(spriteBlinkingTotalTimer >= spriteBlinkingTotalDuration)
{
startBlinking = false;
spriteBlinkingTotalTimer = 0.0f;
this.gameObject.GetComponent<SpriteRenderer> ().enabled = true; // according to
//your sprite
return;
}
spriteBlinkingTimer += Time.deltaTime;
if(spriteBlinkingTimer >= spriteBlinkingMiniDuration)
{
spriteBlinkingTimer = 0.0f;
if (this.gameObject.GetComponent<SpriteRenderer> ().enabled == true) {
this.gameObject.GetComponent<SpriteRenderer> ().enabled = false; //make changes
} else {
this.gameObject.GetComponent<SpriteRenderer> ().enabled = true; //make changes
}
}
}
make changes where i mention and paste the rest of the code as it is, it will work :)
Answer by roofoof500 · Feb 05, 2021 at 06:54 PM
Hey, Im quit late but maybe for people who will search in future, here:
private IEnumerator Blink() {
SpriteRenderer playerSprite = YourPlayerGameObject.GetComponent<SpriteRenderer>();
Color defaultColor = playerSprite.color;
playerSprite.color = new Color(1, 1, 1,1);
yield return new WaitForSeconds(0.05f);
playerSprite.color = defaultColor ;
}
when calling this function, make sure you do like so: StartCoroutine(Blink())
and if you wanna give this an arg and call it do it like so: StartCoroutine("Blink", arg)
Answer by MaxEden · Feb 19, 2021 at 12:58 PM
If anyone still interested there is a small package that does exactly that :) https://assetstore.unity.com/packages/tools/particles-effects/damage-effect-23184