Toggle Menu
Home Blog Projects Newsletter

Space defender - part 2 - the player

Space defender game & code displayed

In the previous part we created the basic structure for our game. In this part we'll start creating the player's ship and make it move and shoot.

The final source code can be found in my GitHub repository And if you want to play the game, you can find it here

Setting up the keyboard

Before we start setting up our player, we need a way to handle keyboard events. For this I've used the keyboard controller found on a PixiJS tutorial from kittykatattack and adapted it to TypeScript. You can find it on my GitHub repository.

We won't go in depth into how it works, because that is out of scope of this project, but what it does is listen for keydown and keyup events and sets a boolean value for each key that is pressed or released. This way we can check in our game loop if a key is pressed or let go, and update our players behavior accordingly.

To use the keyboard controller, download the keyboard.ts file from the commit above and place it in the src/helpers folder of your project.

Creating the player

Now that we have a way to handle keyboard events, we can start creating our player. In a future tutorial we'll make a more complex game and split up our project in multiple files. For now, we'll stick to one file.

Right after where you've initialized your PixiJS application await app.init({ in the main.ts file, add the following code:

const Player = new Graphics();

Player
    .poly([
        0, 0,
        50, 0,
        25, -25,
    ])
    .fill(0x66CCFF);

Player.x = app.screen.width / 2 - Player.width / 2;
Player.y = app.screen.height - 50;

What this will do is create a new Graphics object, draw a triangle with the poly method, fill it with a light blue color and position it at the bottom of the screen.

If you start your game now you'll see a small triangle at the bottom of the screen. But we want to be able to move it around. To do this we need to update the player's position based on the keyboard input.

Moving the player

First we'll need to capture the keyboard input. Add the following code right after where we created our player:

let playerSpeedX = 0;

const arrowLeftHandler = KeyHandler(
    "ArrowLeft",
    () => playerSpeedX = -500,
    () => {
        // To prevent player from stopping moving if the other arrow key is pressed
        if(!arrowRightHandler.isDown) {
            playerSpeedX = 0;
        }
    }
);

const arrowRightHandler = KeyHandler(
    "ArrowRight",
    () => playerSpeedX = 500,
    () => {
        // To prevent player from stopping moving if the other arrow key is pressed
        if(!arrowLeftHandler.isDown) {
            playerSpeedX = 0;
        }
    }
);

What this code does is create two KeyHandlers, one for the left arrow key and one for the right arrow key. When the key is pressed, the player's speed on the x-axis is set to -500 or 500. When the key is released, the player's speed is set to 0. This way we can move the player left and right.

This on it's own wont move the player, we need to update the player's position in the game loop. Replace the app.ticker.add call with the following code:

app.ticker.add((ticker) => {
    const delta = ticker.deltaTime / 100;
    Player.x += playerSpeedX * delta;
});

If you didn't have the app.ticker.add call in your code, you can just add it right after where you defined the KeyHandlers.

Now if you start your game you'll be able to move the player left and right. Great! Let's make it shoot.

Shooting

There are three things we need to think about when we want to make the player shoot:

  1. When the player presses the spacebar, we want to create a new bullet.
  2. We want to update the bullet's position in the game loop.
  3. We want to remove the bullet when it goes out of bounds.

So we need a method that creates a bullet, add it to an array of bullets, updates the bullets position via the game loop and then remove it if it's out of bounds.

Let's start with a method that creates the bullet, add the following code at the bottom of your main.ts file:

let bulletTemplate: PIXI.Graphics | undefined = undefined;
function createBullet(source: PIXI.Graphics) {
    if(!bulletTemplate) {
        bulletTemplate = new Graphics();
        bulletTemplate
            .circle(0, 0, 5)
            .fill(0xFFCC66);
    }

    const bullet = bulletTemplate.clone();
    bullet.x = source.x + 25;
    bullet.y = source.y - 20;
    return bullet;
}

Creating a new Graphics object every time we want to create a bullet is expensive, so we create a template bullet that we clone every time we want to create a new bullet. Cloning is cheaper than creating a new object every time.

We then use the source (who shot the bullet) to position the bullet at the right place, and then return the graphics object.

Okay, so currently, this method isn't being used and nothing is being drawn to the screen. Let's fix that.

We're going to make it so that the player can shoot by pressing space bar, we'll use the KeyHandler for this again. To tell the KeyHandler to use the spacebar, we'll have to give it " " as the key.

Add the following code right after where we defined the KeyHandlers for the left and right arrow keys:

KeyHandler(
    " ",
    () => {
        const bullet = createBullet(Player);
        bullets.push(bullet);
        app.stage.addChild(bullet);
    }
);

This code will create a new bullet when the spacebar is pressed, add it to an array of bullets and add it to the stage, so that we'll see it.

We didn't have the bullets array yet, so let's add that right after where we defined the Player object:

const bullets: PIXI.Graphics[] = [];

Now if you start your game you'll be able to move the player left and right and shoot bullets. But the bullets will stay on the screen forever. Let's fix that. In the gameloop we'll update the bullets position and remove them if they go out of bounds. Add the following code to your game loop, right under where we update the player's position:

for(let i = 0; i < bullets.length; i++) {
    const bullet = bullets[i];
    bullet.y -= 10;

    if(bullet.y < -20) {
        app.stage.removeChild(bullet);
        bullets.splice(i, 1);
    }
}

This part of the code will loop over all the bullets, update their position by moving them up 10 pixels and check if they are out of bounds. If they are, we remove them from the stage and the bullets array.

And that's it! You now have a player that can move left and right and shoot bullets. In the next part we'll create enemies and shoot them down!

Recent articles

Make a simple game using PixiJS and TypeScriptPixiJS setup with Vite and TypeScriptHow Your Coding Skills Can Make a Real Difference in the WorldA guide to writing clean and readable codeAccomplish more with the "Cult of Done"Host your web app for free on Cloudflare PagesFinally got around to making a website for myself