LibGdx: BlinkAction – Action to make any actor blink

In the LibGdx game I am working on, I wanted to make some text blink. There were a couple of gotcha’s that I wasn’t expecting, so I thought I would save all of you some trouble and write a post about it.

First of all, here’s the code for my BlinkAction

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction;

public class BlinkAction extends TemporalAction
{
	private Color baseColor;
	private Color blinkColor;
	private boolean done;
	private float interval;
	private float timeLeftInInterval;
	private boolean isShowingBase;
	

	public BlinkAction(Color baseColor, Color blinkColor, float interval)
	{
		this.baseColor = new Color(baseColor); //Important to copy, not just reference the passed in color
		this.blinkColor = new Color(blinkColor);
		this.interval = interval;
		this.timeLeftInInterval = interval;
		this.isShowingBase = false;
		this.done = false;
	}
	
	public BlinkAction(Color baseColor, Color blinkColor, float interval, float duration)
	{
		this(baseColor,blinkColor,interval);
		setDuration(duration);
		System.out.println("HERE");
	}

	@Override
	public boolean act(float delta)
	{
		super.act(delta);
		
		boolean currentIsShowingBase = isShowingBase;
		
		timeLeftInInterval -= delta;
		if(timeLeftInInterval <= 0)
		{
			timeLeftInInterval += interval;
			isShowingBase = !isShowingBase;
		}
		
		if(done == true)
		{
			getActor().setColor(baseColor);
		}		
		else if(currentIsShowingBase != isShowingBase)
		{
			if(isShowingBase)
			{
				getActor().setColor(baseColor);
			}
			else
			{
				getActor().setColor(blinkColor);
			}
		}		
		return done;
	}
	
	@Override
	protected void update(float percent)
	{
		if(percent >= 1)
		{
			this.done = true;
		}
		
	}

}

The first gotcha was the colors. The Color class in LibGdx is a tricky one. You have to make sure that whenever you write a class that stores a color, your local variable must be a copy of that Color, NOT a reference.

The second gotcha is that because this uses Actor.setColor(Color), this will only work on actors that are not all, or mostly black. The setColor() function tints the existing colors with the value that you pass in, it doesn’t replace them.

One thought on “LibGdx: BlinkAction – Action to make any actor blink

  1. Pingback: jersgamneds

Leave a Reply

Your email address will not be published. Required fields are marked *