In a previous post I showed you how to set up a PixiJS project with Vite and TypeScript. In this post, we will create a simple space defender game building on top of that setup.
For this project I assume you have a basic knowledge of how to program in TypeScript/JavaScript. And because we're focusing on PixiJS I won't focus too much on the HTML/CSS side of things.
The final source code can be found in my GitHub repository and if you want to play the game, you can find it here.
If you haven't set up a PixiJS project with Vite and TypeScript yet, I recommend you to read my previous post first in which I explain how to set it up and get it to run.
Let's quickly setup the index.html
file with the content that we need for this project. Replace the content of the <div id="app"></div>
element with the following:
<div id="app">
<div id="gameHud">
<div>
Lives: <span id="gameLives"></span>
</div>
<div>
Level: <span id="gameLevel"></span>
</div>
<div>
Score: <span id="gameScore"></span>
</div>
</div>
<div id="game">
</div>
</div>
This will be the structure of our game, we have a HUD (Heads Up Display) that will show the player's lives, level, and score. And a game container where we will render the game. In part 4 we'll start making use of this.
Next up, we need to apply some CSS to this so that it's nicely displayed on the screen. Navigation to the stylesheet called styles.css
in the src
folder and add the following content:
body {
margin: 0;
background-color: darkgrey;
}
#app {
height: 100vh;
width: 480px;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#gameHud {
display: flex;
width: 100%;
padding: 10px;
background-color: #333;
color: white;
> div {
flex: 1;
}
}
Great! Now that we have the basic structure in place, let's start by creating the game screen. We need to have a variable that holds the game container element so that the game knows where to insert the game canvas into the DOM.
(async () => {
let gameContainer = document.getElementById("app");
// ....
});
After that we need to update our app size to match the game size we want, in our case we want a game that is 480 wide and 720 high. So we need to update the app.init
call to match that size.
await app.init({
width: 480,
height: 720,
});
And then replace
document.body.appendChild(app.canvas);
with
gameContainer.appendChild(app.canvas);
We now have a game screen that is 480x720 pixels in size and is displayed in the center of the screen.
In the next part we'll start creating the player's ship and make it move and shoot.