Friday, April 12, 2019

Add sprite flickering to a LibGDX object


How can I make a LibGDX Actor object flicker over a set duration?


Many 2D platformers have the player character 'flicker' after taking damage to indicate temporary invincibility, (ie: invincibility frames). For an example, see the below gif from Shovel Knight.


Player taking damage from an enemy


It's fairly simple to make an object fade in or out over time using LibGDX's Actions library.


Actor player = new Actor();
// fade out in 0.25 seconds
player.addAction(Actions.fadeOut(0.25));


But searching through the documentation, I couldn't find any method for Actions.flicker(). How can I implement sprite flickering in LibGDX?



Answer



Create a flickering SequenceAction and have it repeat a preset number of times.


flicker effect in action


import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;

if (playerDamaged) {
SequenceAction flicker = new SequenceAction(Actions.fadeOut(0.25f), Actions.fadeIn(0.25f));

player.addAction(Actions.repeat(6, flicker));
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...