Pixi.js Tutorial #5: Your First Mini Game, From Start to Finish

Let’s build a complete, working mini game!
You’ve learned about sprites, animation, UI — now it’s time to put them together.

We’ll make a simple avoid-the-obstacle game using everything we’ve covered so far.


🧠 The Plan

🟢 The player: A sprite you can move left and right.
🔴 The obstacle: Falls from the top of the screen.
💥 Game over: If you touch an obstacle.
✅ Win: Survive as long as possible!


🔧 Step 1. Setup the Stage

<script src="https://pixijs.download/release/pixi.min.js"></script>
<canvas id="game-canvas"></canvas>
const app = new PIXI.Application({
view: document.getElementById('game-canvas'),
width: 360,
height: 540,
backgroundColor: 0x1099bb
});

🧍 Step 2. Add the Player

const player = new PIXI.Graphics();
player.beginFill(0xffffff);
player.drawRect(0, 0, 40, 40);
player.endFill();
player.x = app.screen.width / 2 - 20;
player.y = app.screen.height - 60;
app.stage.addChild(player);

Use arrow keys to move:

window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft') player.x -= 10;
if (e.key === 'ArrowRight') player.x += 10;
});

🌩️ Step 3. Spawn Falling Obstacles

const obstacles = [];

function spawnObstacle() {
const obs = new PIXI.Graphics();
obs.beginFill(0xff4444);
obs.drawRect(0, 0, 40, 40);
obs.endFill();
obs.x = Math.random() * (app.screen.width - 40);
obs.y = -40;
app.stage.addChild(obs);
obstacles.push(obs);
}

setInterval(spawnObstacle, 1000); // one per second

🔁 Step 4. Game Loop and Collision

app.ticker.add(() => {
obstacles.forEach((obs) => {
obs.y += 4;

if (
obs.y + 40 > player.y &&
obs.x < player.x + 40 &&
obs.x + 40 > player.x
) {
alert('Game Over!');
location.reload(); // refresh to restart
}
});
});

Boom. You just made a game.


🎁 Bonus: Score!

let score = 0;
const scoreText = new PIXI.Text('Score: 0', {
fill: 'white',
fontSize: 20
});
scoreText.x = 10;
scoreText.y = 10;
app.stage.addChild(scoreText);

setInterval(() => {
score++;
scoreText.text = `Score: ${score}`;
}, 1000);

✅ What You’ve Built

  • Full playable game (no frameworks, just Pixi.js)
  • Controls, collision, obstacle logic
  • Score tracking and game reset

🎉 It’s not AAA, but it’s yours. And it works.


🧪 Want to go further?

Try these:

  • Add a start screen
  • Add lives or health
  • Animate the player (see Part 3!)
  • Save scores to a database
  • Make it ridiculously hard 😈