Blinking/flashing effects

We’ll make a sprite blink with alpha and a tint fill 3 times, 1 second apart (▄█▄█▄█).

Here are 2 techniques.

Timeline

We add an empty event at the end of the timeline as a delay before repeating, and make 2 repeats.

:person_tipping_hand: Remember to destroy timelines when done with them.

const timeline = this.add.timeline([
  {
    at: 0,
    target: image,
    set: {
      alpha: 0.5,
      tint: 0x00ffff,
      tintFill: true
    }
  },
  {
    at: 500,
    target: image,
    set: {
      alpha: 1,
      tint: 0xffffff,
      tintFill: false
    }
  },
  {
    // A delay before repeating.
    at: 1000
  }
]);

timeline.repeat(2).play();

timeline.on("complete", timeline.destroy);

Timer event

For 3 blinks, we make 5 repeats, for 6 callbacks in all, since we alternate between 2 states.

We use startAt identical to delay so the first callback starts immediately.

We check the timer’s repeatCount in the callback to figure whether we’re blinking on or off.

const timerEvent = this.time.addEvent({
  delay: 500,
  startAt: 500,
  repeat: 5,
  args: [image],
  callback: function (image) {
    // `this` is the timer event.
    // `this.repeatCount` goes from 5 to 0.
    if (this.repeatCount % 2 === 0) {
      // Clear on repeats 4, 2, 0.
      image.clearAlpha().clearTint();
    } else {
      // Tint on repeats 5, 3, 1.
      image.setAlpha(0.5).setTintFill(0x00ffff);
    }
  }
});
2 Likes