Developing a Javascript Video Game: Part 2

by admin admin Date: 06-03-2019 javascript video game course tutorial


This article is the second part of a Javascript game tutorial.

Here you can read the first part

Let's create the spaceship

Now that the background is finished, we can start setting up our space vehicle! Let's create a Player.js file and add it as a script to index.html.

In essence, we want this ship to appear near the screen's left border. We also need its anchor (position of the object) in the center of the sprite, and we can rescale it because it is perhaps too large:

class Player
{
    constructor()
    {
        this.sprite = new PIXI.Sprite(PIXI.loader.resources["assets/spaceship.png"].texture);
        this.sprite.interactive = true;

        this.sprite.anchor.set(0.5, 0.5);
        this.sprite.position.set(renderer.width * 0.2, renderer.height * 0.4);
        this.sprite.scale.set(0.4, 0.4);

        stage.addChild(this.sprite);
    }
}

We must declare this object in the main.js file as a global variable so that it can be instantiated in the game:

var stage = new PIXI.Container();
var cloudManager;
var player;
...

And also in the init function of the same file:

player = new Player();

You should now see the glittering cruise of the spaceship. However, if you wait a few seconds, you should have some problems:

The spaceship now is flying behind the clouds...=_=

Yeah, because the last created object is actually moving behind the previous object. After the spacecraft is instantiated, clouds are spawning, so we need the cloud manager to generate clouds at the bottom of the object list. For this, we only need to update the CloudManager class addChild:

stage.addChildAt(this.cloud, 0);

addChildAt actually allows us to pass a second parameter, that is the position in the stage’s objects list. The furthest it is, the furthest the sprite will be on the screen.

"0" basically means the first index in the list of objects, so every time we create a new cloud, we add it to the first position of the list to make sure it appears behind the spacecraft.

Now, we can start the spaceship controls.

Let's move the spaceship

Let’s work with Player.js class and add some code in the constructor:

window.addEventListener('keydown', this.onKeyDown.bind(this));
window.addEventListener('keyup', this.onKeyUp.bind(this));

This allows the game to capture keyboard events (when pressing and releasing a key). If one of these events occurs, the method is executed at the end of each line.

Now, we have to define 2 empty methods in the same class (we will fill these ones in a little while):

onKeyDown(key) = {};
onKeyUp(key) = {};

We also need 3 variables to move the spaceship: its horizontal and vertical directions (X & Y) and the speed (all of them in the constructor):

this.directionX = 0;
this.directionY = 0;
this.speed = 8;

this.keyCodes = {37: -1, 38: -1, 39: 1, 40: 1};

This object is essentially a combination of key codes and values of direction:

  • the number 37 corresponds to left arrow key, to move our spaceship to the left we need to decrease its X position.
  • the number 38 corresponds to up arrow key, to move our spaceship to the top we need to decrease its Y position.
  • the number 39 corresponds to: is the right arrow key, to move our spaceship to the right we need to increase its X position.
  • number 40 corresponds to is the down arrow key, to move our spaceship to the bottom we need to increase its Y position.

Whenever a key is pressed, the appropriate direction is retrieved:

onKeyDown(key)
{
    if (key.keyCode == 37 || key.keyCode == 39)
        this.directionX = this.keyCodes[key.keyCode];
    else if (key.keyCode == 38 || key.keyCode == 40)
        this.directionY = this.keyCodes[key.keyCode];
}

It looks pretty strange, but let's explain: If the key code is 37 or 39 (which means the left or right arrow key), then the X direction is set. If it's 38 or 40, you can guess what's going on (yes, it's vertical).

Now we add the update method of the player:

update()
{
    this.sprite.position.x += this.directionX * this.speed;
    this.sprite.position.y += this.directionY * this.speed;
}

IMPORTANT: don’t forget to call it in the loop function of main.js!

player.update();

If you save the game and reload it works well, except that when we release the direction keys, the ship keeps moving. It's quite evident because we haven't completed the onKeyUp function, which catches the key just released. And so, by setting either directionX or directionY to 0, we can stop it.

There's only one tiny problem: What happens if we set the direction to 0 because we released the left key, but the right key is still pressed?

The spaceship will stop, and we'd have to press the right key to move again, which is not very practical.

So why not check whether the right key or left key is still pressed so that we can reset the direction of the previous key?

What are we going to do? Firstly, we need to store the state of each key in a boolean, pressed or released. Let’s put all these states in an object variable in the Player constructor:

this.keyState = {37: false, 38: false, 39: false, 40: false};

If a key is pressed, then we just change its state to true, and if it’s released we set it to false.

Let’s add this line at the beginning of onKeyDown:

this.keyState[key.keyCode] = true;

and now, this line in onKeyUp:

this.keyState[key.keyCode] = false;

We can now proceed with the onKeyUp logic: If one of the horizontal or vertical keys is released, but the other key is still pressed, we change the direction to the last one. If both are released, we will stop the ship:

if (!this.keyState[37] && this.keyState[39])
    this.directionX = this.keyCodes[39];
else if (this.keyState[37] && !this.keyState[39])
    this.directionX = this.keyCodes[37];
else this.directionX = 0;

if (!this.keyState[38] && this.keyState[40])
    this.directionY = this.keyCodes[40];
else if (this.keyState[38] && !this.keyState[40])
    this.directionY = this.keyCodes[38];
else this.directionY = 0;

We have all set! Now, save, reload and enjoy!

Shooting rockets

What are we are miss now?

Sure! We want to shoot rockets now that we can control the ship.

Let’s start by adding the spacecraft in the assets folder and then add it to the assets loader:

PIXI.loader.add([
    "assets/cloud_1.png",
    "assets/cloud_2.png",
    "assets/spaceship.png",
    "assets/rocket.png"
]).load(init);

Now, we'll create a new file called Rocket.js in the src folder and add it in index.html:

<script src="../src/lib/pixi.min.js"></script>
<script src="../src/Player.js"></script>
<script src="../src/CloudManager.js"></script>
<script src="../src/Rocket.js"></script>
<script src=“../src/main.js"></script>

Let’s go back to the Player class. We want it to be able to shoot a rocket if he presses the spacebar button. The onKeyDown function is already catching such events, so we just need to make a condition with the key code we want (spacebar in this example):

onKeyDown(key)
{
    this.keyState[key.keyCode] = true;

    if (key.keyCode == 32) {
        let rocket = new Rocket(this.sprite.position.x,
        this.sprite.position.y);
    }

    if (key.keyCode == 37 || key.keyCode == 39)
        this.directionX = this.keyCodes[key.keyCode];
    else if (key.keyCode == 38 || key.keyCode == 40)
        this.directionY = this.keyCodes[key.keyCode];
}

We simply give the spaceship position in the Rocket constructor, so we only set its position inside the spaceship one. So, let's initialize Rocket.js with the constructor:

class Rocket
{
    constructor(x, y)
    {
        this.sprite = new PIXI.Sprite(PIXI.loader.resources["assets/rocket.png"].texture);

        this.sprite.anchor.set(0.5, 0.5);
        this.sprite.position.set(x + 40, y);

        stage.addChild(this.sprite);
    }
}

Alright, if you save & reload, you may be able to fire rockets by pressing the spacebar!

Next post soon!

If you missed it, read the first part.

Read:  Developing a JavaScript video game: Part  3

 

 

 

Original post by  Baptiste M. 

Background vector created by photoroyalty - www.freepik.com

 
by admin admin Date: 06-03-2019 javascript video game course tutorial hits : 2583  
 
 
 
 

Related Posts