Hi everybody! This article is the second part of my tutorial to make a little game with Javascript. You can read Part 1 here.
The full source code of this tutorial can be found here.
Now that the background is done, we can finally start setting up our spaceship!
Let’s create a Player.js file and add it to index.html as a script (same as CloudManager).
Here is a (beautiful) spaceship designed in a few minutes that you can add to your assets folder and in the loader function of main.js:
Spaceship
Basically, we want this ship to appear near the left border of the screen. We also need its anchor (position point of the object) to be in the center of the sprite, and because its maybe too huge, we can rescale it:
Of course, we have to declare this object as a global variable of the main.js file, so it can be instantiated in the game:
… and in the init function of the same file (just after CloudManager):
Now you should see the glittering spaceship cruising.
However if you wait for a few seconds, you should get some troubles:
The spaceship is flying behind the clouds!
Yeah, because in fact, the last object created is moving behind the previous one. Clouds are spawning after the spaceship has been instantiated, so we need the cloud manager generating clouds in the bottom of the objects list. For this, we just have to update a bit the addChild of the CloudManager class:
addChildAt allows us to pass a second parameter, which is the position in the stage’s objects list. The furthest it is, the furthest the sprite will be on the screen.
“0” means the first index in the objects list, so each time we create a new cloud, we add it at the first position of the list, ensuring that it will appear behind the spaceship.
Now that it’s done, we can start the spaceship controls.
Let’s get back to Player.js class and add some lines in the constructor:
This allows the game to catch keyboard events (when a key is pressed and released). When one of this event occurs, the method at the end of each line is executed.
Note: By adding “.bind(this)” at the end of the function, we pass the context of the object into it, which means we can still access its properties by calling “this”. If we don’t write it this way, the callback function is not able to determine which object we are working with. Just remember that if one of your callback function is getting an “undefined this” error, you might have to bind your object like this.
Let’s define 2 empty methods in the same class (we will fill these ones in a little while):
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 object is basically an association of key codes and direction values:
Every time a key is pressed, we retrieve the corresponding direction:
It’s looking pretty weird but let’s explain that: if the key code is 37 or 39 (which means left or right arrow key), then we just set the X direction. If it’s 38 or 40, you can guess what’s happening (yeah it’s actually the vertical direction). That’s all!
Let’s add the update method of the player (like the Cloud Manager, remember?):
… and of course, don’t forget to call it in the loop function of main.js!
If you save and reload the game, it (should) work well, except that the ship keeps moving when we release the direction keys. It’s obvious because we didn’t complete the onKeyUp function, which is catching the key that has just been released. So this way we can stop it by setting either directionX or directionY to 0.
There is just one little problem there: what’s going on if we set the direction to 0 because we released the left key, but the right key is still pressed?
Yeah, the spaceship is going to stop, and we would have to press the right key again to move, which is not very logic.
So why not check if the right key or left key is still pressed, so we can reset the direction to this previous pressed key?
That’s what we are going to do. And for this we need to store the state of each key in a boolean, pressed or released (true or false). Let’s put all these states in an object variable in the Player constructor:
If a key (identified by its own code) is pressed, then we just change its state to true, and if it’s released we set it to false. Easy, right?
Let’s add this line in the beginning of onKeyDown:
… and this one in onKeyUp:
Now we can continue with the onKeyUp logic: if one of the horizontal or vertical key is released but the opposite one is still pressed, we change the direction to the last one. If both of them are released, we stop the ship:
Note: There are multiple ways of handling the spaceship move, this is certainly not the cleanest one, but I think it’s one of the simplest to understand.
We’re all set, save & reload & enjoy!
Upgrade: The spaceship can exit the screen! Try to check its position before updating it. You can check the result here.
Now that we can control the ship, we want it to shoot rockets.
Let’s start by adding the sprite in the assets folder:
… and add it to the assets loader as usual:
Create a new file called Rocket.js in the src folder and add it in index.html with the others guys:
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):
We are giving the spaceship position in the Rocket constructor, so inside we just set its position to the spaceship one (with an offset to make it appear in front of the ship instead of the middle).
So let’s go, initialize Rocket.js with the constructor:
Alright, if you save & reload, you may be able to fire (static) rockets by pressing the spacebar!
To make them move, we need to create an array variable containing all the rockets existing in the game (we don’t know how many of them are on stage):
The _list variable is located outside of the class because it’s static, which means its value is unique and is not only one object’s property (unlike this). However we can get it and set it as we want (with the 2 first lines of the class).
We can push the current object inside this list (within the constructor) and declare the speed variable in the same time:
… and also add the update method:
This is basically the same as before, we update the x position of the rocket (and not the y because it’s not moving vertically) and like the clouds, we remove it when it goes outside of the screen limits, except that this time it’s the right edge.
After that, in the loop of main.js, we just have to parse the rocket list and call the update function for each element:
Save & reload, and try it!
It’s shooting, but it isn’t automatic. You have to press the key for each rocket and when you don’t move, it’s kinda weird because it’s firing fast as hell. What we want is to be able to shoot automatically when the key is kept pressed, with an adjustable speed.
Let’s define two new variables in the Player constructor: the fire speed (that can be modified) and the cooldown, which is going to be the timer value:
We also need to update keyState to add the space key, because we want to know if it’s pressed or not:
Here is the function we are using to shoot (we need to call it in the update of the player):
It’s pretty simple here: we just increment the timer from 0 to the fire speed we set and if the key is pressed and the timer has reached the value, we spawn a rocket and reset the timer to 0.
This function is permanently executed in the update loop of the player:
Work done! If you want it faster, just decrease the fire speed variable (and increase it for slower speed).
Firing some rockets
Thank you for reading!
If you have any questions or suggestions, please let me know so I can improve the next one!