Milestone 3: Fireflies
The game is developing nicely: there's a hero that can move around, and it needs to dodge obstacles. However, there are no stakes to the game yet: nothing to do, no way to win, and no way to lose. Let's start adding the way of winning, by making fireflies that need to be collected.
Our First Firefly
Making a firefly is easy: we just need an actor with a rigidBody and an appearance.
We know we're going to end up making a lot of them, so let's create a function that takes the coordinates of the center of a firefly, and draws it there:
/**
* Make one firefly at (cx, cy). For now, it's a light gray box with a label, on a round rigid body.
*
* @param cx The X coordinate of the firefly's center
* @param cy The Y coordinate of the firefly's center
*/
function makeFirefly(cx: number, cy: number) {
new Actor({
appearance: [new FilledBox({ width: 0.55, height: 0.55, fillColor: "#d1d5db" }), new TextSprite({ center: true, face: "Arimo Regular", size: 11, color: "#111827" }, "firefly")],
rigidBody: new CircleBody({ cx, cy, radius: 0.3 }),
});
}
To test this out, let's make one firefly when the game starts:
// One firefly is already lit when the game starts
makeFirefly(5.5, 4.5);
Catching The Firefly
If you try to collect the firefly, you'll find that you can't.
The hero just walks right over it.
To fix that, give the firefly a CollectableBehavior.
new Actor({
appearance: [new FilledBox({ width: 0.55, height: 0.55, fillColor: "#d1d5db" }), new TextSprite({ center: true, face: "Arimo Regular", size: 11, color: "#111827" }, "firefly")],
rigidBody: new CircleBody({ cx, cy, radius: 0.3 }),
behaviors: new CollectableBehavior({ onCollect: "fireflies" }),
});
The CollectableBehavior does two things.
First, it makes the firefly disappear when the hero collides with it.
Second, it tells JetLag to make sure there is a counter called "fireflies", and to add one to that counter.
Later, you'll learn how to show the counter.
Making Many Fireflies
The game will be more fun with lots of fireflies, so let's set up a timer that makes them periodically.
Like before, since there's a number that we might want to adjust later, we'll make it a constant.
SPAWN_FREQ will determine how many seconds pass between any two firefly spawns.
We'll use it with a timer that repeats, so the timer will make fireflies at a regular cadence.
We'll introduce another number: GLOW_RADIUS.
This tracks how big the firefly will be.
When we make fireflies, we will want to put them in random places.
We don't want them hanging off the edge of the screen, though.
So we can't say "put the center X between 0 and 16 and the center Y between 0 and 9".
Instead, we need to factor the radius into the decision.
For example, the center X should be less than 16 - GLOW_RADIUS and greater than GLOW_RADIUS.
// How often a new firefly blinks on
const SPAWN_FREQ = 1.3;
// How far a firefly's glow reaches, in meters
const GLOW_RADIUS = 0.45;
Now let's use that value to control a timer that makes fireflies.
Math.random() picks a number i such that .
We can multiply it by a whole number, and we can add or subtract to shift it.
For example, if you wanted a number between 8 and 12, you'd use 8 + Math.random() * 4.
Using that knowledge, we can make random fireflies that never go off screen:
// A new firefly blinks on every so often, somewhere on the screen. (The glow has to stay on the screen, so the spot
// can't be closer to an edge than the glow's radius.)
stage.world.timer.addEvent(new TimedEvent(SPAWN_FREQ, true, () => {
makeFirefly(GLOW_RADIUS + Math.random() * (16 - 2 * GLOW_RADIUS), GLOW_RADIUS + Math.random() * (9 - 2 * GLOW_RADIUS));
}));
// One firefly is already lit when the game starts
makeFirefly(5.5, 4.5);
Paying Attention To Firefly Placement
Randomness is one of the trickiest things in a game. It helps to keep a game feeling fresh and different, so that it remains playable for longer. However, when something is truly random, that means even things you don't want to happen become possible.
Start up your game, and don't move the hero. Watch the fireflies. Did any appear on the hero? On another firefly? On a hedge or tree?
In short, when we pick a random position, we need to make sure there's nothing close to it. Fortunately, the underlying physics simulation makes this easy. Whenever we pick a spot, we can simply ask it "is there anything too close to this spot", and if so, we can try again. Here's that logic, wrapped up in a nice, reusable function. The key point is that we ask for every actor near the point we choose. We get back an array. If the array length is 0, there's nothing close by, so the spot is good.
/**
* Pick a random spot where a firefly fits: all of its glow is on the screen, and nothing else (a hedge, a tree, the
* jar, the hero, or another firefly) is in the way
*
* @param glowRadius How far the firefly's glow reaches, in meters
*
* @returns The cx/cy of an available spot
*/
function randomOpenSpot(glowRadius: number) {
while (true) {
// Keep the whole glow on the screen, which is 16 meters wide and 9 meters tall
const cx = glowRadius + Math.random() * (16 - 2 * glowRadius);
const cy = glowRadius + Math.random() * (9 - 2 * glowRadius);
// Ask the world what's near that spot, in a square the size of the glow. If the answer is "nothing", we're done.
// Otherwise, pick a different spot.
if (stage.world.physics.actorsAt({ x: cx, y: cy }, 2 * glowRadius).length == 0) return { cx, cy };
}
}
Now we can update the timer for making fireflies:
// A new firefly blinks on every so often, somewhere in the open
stage.world.timer.addEvent(new TimedEvent(SPAWN_FREQ, true, () => {
const spot = randomOpenSpot(GLOW_RADIUS);
makeFirefly(spot.cx, spot.cy);
}));
// One firefly is already lit when the game starts
makeFirefly(5.5, 4.5);
Making Fireflies Disappear
If fireflies stick around forever, two bad things are going to happen. First, the game will be too easy. Second, as the screen gets polluted with fireflies, it will become harder and harder to find a spot to make a new one. Eventually the game will start to lag.
For both reasons, we want to remove fireflies after a little while. While we're at it, we should make them flicker right before departing, to give a visual clue to the player.
Since numbers always need adjusting later on, let's start by putting two numbers into the game as constants, so we can fine-tune them later:
// How long a firefly stays lit
const FIREFLY_LIFETIME = 4;
// How long a firefly flickers, as a warning, before it goes out
const FLICKER_TIME = 1.2;
Now let's adjust the makeFirefly function.
We'll pass these numbers to it (because in the future, we might want different kinds of fireflies that flicker for different amounts of time).
Inside the function, we'll add another timer that runs every 0.1 seconds.
Normally it just counts until the time when we remove the firefly.
But when the timer gets close to disappearing (within flickerTime seconds remaining), we'll swap its color back and forth:
/**
* Make one firefly at (cx, cy). It has a CollectableBehavior, so when the hero touches it, it disappears, and the
* "fireflies" counter goes up by one. It doesn't wait around forever: it blinks out on its own after `lifetime` seconds. For the
* last `flickerTime` seconds of its life it flickers, so the player gets a warning that it's about to go.
*
* @param cx The X coordinate of the firefly's center
* @param cy The Y coordinate of the firefly's center
* @param lifetime How many seconds before it blinks out on its own
* @param flickerTime How many seconds, at the end of its life, it flickers
*/
function makeFirefly(cx: number, cy: number, lifetime: number, flickerTime: number) {
// For now, a firefly is a light gray box with a label on it
const box = new FilledBox({ width: 0.55, height: 0.55, fillColor: "#d1d5db" });
const firefly = new Actor({
appearance: [box, new TextSprite({ center: true, face: "Arimo Regular", size: 11, color: "#111827" }, "firefly")],
rigidBody: new CircleBody({ cx, cy, radius: 0.3 }),
behaviors: new CollectableBehavior({ onCollect: "fireflies" }),
});
// For the very last half second, the flicker gets twice as fast
const fastFlickerTime = 0.5;
// Every tenth of a second, this timer adds 0.1 to the firefly's age, and
// decides what the firefly should look like right now.
let age = 0;
const ticker = new TimedEvent(0.1, true, () => {
age += 0.1;
if (age >= lifetime) {
// Its time is up: remove the firefly, and stop this timer. (If the
// hero already caught it, removing it again does no harm.)
firefly.remove();
ticker.cancelled = true;
} else if (age >= lifetime - flickerTime) {
// It's almost out of time, so flicker. `Math.floor(age * 5) % 2` flips
// between 0 and 1 every 0.2 seconds, and for the last `fastFlickerTime`
// seconds, `* 10` makes it flip twice as fast. When `on` is true, the
// box is solid gray. When it's false, it dims by becoming mostly
// see-through ("30").
const on = Math.floor(age * (age >= lifetime - fastFlickerTime ? 10 : 5)) % 2 == 0;
box.fillColor = on ? "#d1d5db" : "#d1d5db30";
}
});
stage.world.timer.addEvent(ticker);
}
Now we just need to update the call to makeFirefly so that it has the extra values, and our fireflies should flicker before disappearing:
// A new firefly blinks on every so often, somewhere in the open
stage.world.timer.addEvent(new TimedEvent(SPAWN_FREQ, true, () => {
const spot = randomOpenSpot(GLOW_RADIUS);
makeFirefly(spot.cx, spot.cy, FIREFLY_LIFETIME, FLICKER_TIME);
}));
// One firefly is already lit when the game starts
makeFirefly(5.5, 4.5, FIREFLY_LIFETIME, FLICKER_TIME);
End State
You're done with the third milestone! If you want to compare your code to mine, here's my Firefly Jar Milestone 3 code.
Here's my version of the game. Be sure to compare it against yours: