Table of Contents
PixiJS Setup with Vite and TypeScript
Mr. Linxed ・ Apr 20
Accomplish more with the "Cult of Done"
Mr. Linxed ・ Feb 18
Home Web Front-end JS Tutorial Space Defender - part the player

Space Defender - part the player

Jul 21, 2024 am 08:45 AM

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 the 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;
Copy after login

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;
        }
    }
);
Copy after login

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;
});
Copy after login

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;
}
Copy after login

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);
    }
);
Copy after login

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[] = [];
Copy after login

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 


<p>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.</p>

<p>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!</p>

<hr>


<div class="ltag__link">
  
    <div class="ltag__link__pic">
      <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172152276283279.png" class="lazy" alt="Space Defender - part  the player" loading="lazy">
    </div>
  
  
    <div class="ltag__link__content">
      <h2 id="PixiJS-Setup-with-Vite-and-TypeScript">PixiJS Setup with Vite and TypeScript</h2>
      <h3 id="Mr-Linxed-Apr">Mr. Linxed ・ Apr 20</h3>
      <div class="ltag__link__taglist">
        #webdev
        #javascript
        #beginners
        #tutorial
      </div>
    </div>
  
</div>



<div class="ltag__link">
  
    <div class="ltag__link__pic">
      <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172152276283279.png" class="lazy" alt="Space Defender - part  the player" loading="lazy">
    </div>
  
  
    <div class="ltag__link__content">
      <h2 id="Accomplish-more-with-the-Cult-of-Done">Accomplish more with the "Cult of Done"</h2>
      <h3 id="Mr-Linxed-Feb">Mr. Linxed ・ Feb 18</h3>
      <div class="ltag__link__taglist">
        #productivity
        #beginners
        #discuss
        #motivation
      </div>
    </div>
  
</div>




<hr>

<p>Don't forget to sign up to my newsletter to be the first to know about tutorials similar to these.</p>


          

            
  

            
        
Copy after login

The above is the detailed content of Space Defender - part the player. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles