HTML Canvas Games from Scratch #3
Tags: html, javascript, gamedev, physics
Published: 2020-04-17 21:06:10

<img src="https://www.thefactsite.com/wp-content/uploads/2014/11/space-invaders-we-come-in-peace.jpg">
Hey devs!:video_game:
So we are all set to begin creating the game:space_invader:.
Let's do it!💥
## Phase 3
Before we jump into coding, let us plan things.
**Objects** we will need :
- **Player (The space shuttle)**:rocket:
- **Alien**:space_invader:
- **Bullets**🔫
	
Let us define these objects :
```js
//Shuttle object
var shuttle = function(x,y){
	this.x = x;
	this.y = y;
}

//Alien object
var alien = function(x,y){
	this.x = x;
	this.y = y;
}

//Bullet object
var bullet = function(x,y){
	this.x = x;
	this.y = y;
}

//Since we will handle multiple bullets and Aliens
var Bullets = new Array();
var Aliens = new Array();
```
Other variables that we will need to define are : 
```js
var totalBullets = 0; 		//bullets on screen
var health = 90;			//health of player
var kills = 0;				//total aliens killed
var maxAliens = 5;			//Max aliens on the screen
var bulletSpeed = 7;		//Speed of the bullet
var alienSpeed = 0.2;		//Speed of the aliens
```
> Note : These values are selected by hit and trial.

Now we will need alien and shuttle sprites. I have already made these using fillRect() functions.
Download code from this link : **[Code Link](https://github.com/jrathod9/Making-of-Space-X-/tree/master/Phase%203/Sprites)**
Location in repository : **\Phase 3\Sprites**
> Note : It is ok if you don't try to understand drawShuttle() and drawAlien() as it isn't very important, those are just figures made using rectangles. You will be using images for sprites in the future mostly.

Result : 
<center><img src="https://github.com/jrathod9/Making-of-Space-X-/blob/master/Phase%203/Sprites/sprites.png?raw=true" width="600"></center>

> Space Shuttle will be positioned at the **bottom center**.
>Alien will have a constrained random position at approximately the **top part** of the screen.
   
   **Now we will work on the same code that you've downloaded.**
   Let us add an event listener to enable the space shuttle to move using 	the arrow keys. (As we did in the previous post)
```js
var keys = [];		//Add this before the draw() definition

window.addEventListener("keydown", keysPressed, false );

function keysPressed(e) {
	// store an entry for every key pressed
	keys[e.keyCode] = true;
window.addEventListener("keyup", keysReleased, false);
}
 
function keysReleased(e) {
    // mark keys that were released
	keys[e.keyCode] = false;
}        
```
So we need to adjust the position of the space shuttle before re-drawing it on the canvas. Inside the draw() function, before drawing the space shuttle : 
```js
//Handling arrow key presses and shuttle movement boundaries 
		
	// left
	if (keys[37]) {
		if(player.x >= 70)
		player.x -= shuttleSpeedh;
	}
	   
	// right
	if (keys[39]) {
		if(player.x <= window.innerWidth - 50)
			player.x += shuttleSpeedh;
	}
	   
	// down
	if (keys[38]) {
		if(player.y >= window.innerHeight/2)
			player.y -= shuttleSpeedv;
	}
	   
	// up
	if (keys[40]) {
		if(player.y <= window.innerHeight - baseBottomh - midBottomh - cannonh)
			player.y += shuttleSpeedv;
	}
```  
Run this code to check what are the **constraints** to the movement of the space shuttle.   
> Note : shuttleSpeedh and shuttleSpeedv respresent horizontal and vertical velocity. These have been defined in the file at the top.

Result : 
<img src="https://github.com/jrathod9/Making-of-Space-X-/blob/master/Phase%203/MovingShuttle/MovingShuttle.gif?raw=true">
Here's the source code : **[Code link](https://github.com/jrathod9/Making-of-Space-X-/tree/master/Phase%203/MovingShuttle)**
Location in repository : **\Phase 3\MovingShuttle**

Now let us fill the array of aliens: 
```js
//Initial array of aliens
for(a = 0; a < maxAliens; a++){
	var temp = new alien(Math.random()*(window.innerWidth-100)+60, Math.random()*(window.innerHeight/2-300));
	Aliens.push(temp);	//We already defined this array
}
```
To draw all these aliens we need to make changes in out draw() function. Just add a loop where we are drawing a single alien:
```js
for(a = 0 ; a < Aliens.length ; a++)
		drawAlien(Aliens[a]);
```
Result : 
<img src="https://github.com/jrathod9/Making-of-Space-X-/blob/master/Phase%203/SpawnAliens/maxaliens.png?raw=true">
Here's the source code : **[Code Link](https://github.com/jrathod9/Making-of-Space-X-/tree/master/Phase%203/SpawnAliens)**
Location in repository : **\Phase 3\SpawnAliens**

Moving on, we now need to make the space shuttle launch bullets.
This will happen on pressing **spacebar**. But only 1 bullet will be launched on pressing spacebar once. So the event we use will be keyRelease. Remember we have already defined it?
 Let us add more functionality to it.
 ```js
 function keysReleased(e) {
	 if(e.keyCode==32){				//keycode of spacebar
			var temp = new bullet(player.x , player.y - midBottomh - cannonh);
			totalBullets++;
			Bullets.push(temp);
	}
}
 ``` 
Now let us draw all the bullets on the canvas;	
```js
function drawBullet(thisBullet){
	c.fillStyle = bulletColors[Math.floor(Math.random()*6)];
	c.beginPath();
	c.arc(thisBullet.x,thisBullet.y - cannonh + 10, 2.5 , 0 , Math.PI*2 ,false);
	c.fillRect(thisBullet.x-2.5,thisBullet.y - cannonh + 10  ,5,5);
	c.closePath();
	c.fill();
}
```

Last but not the least lets draw these bullets on the canvas and make them move . This should be added inside draw(): 
```js
//Check bullets that left the screen and remove them from array
for(a = 0 ; a < Bullets.length ; a++){
	if(Bullets[a].y <=0 ){
		Bullets.splice(a,1);			//Removes 1 element from the array from index 'a'
	}	
}	

//Update bullet coordinates to make it move and draw bullets
for(a = 0 ; a < Bullets.length ; a++){
	Bullets[a].y -= bulletSpeed;		//Already defined at the top
	drawBullet(Bullets[a]);
}	
``` 
Result : 
<img src="https://github.com/jrathod9/Making-of-Space-X-/blob/master/Phase%203/Bullets/Bullets.gif?raw=true">
Here's the source code : **[Code link](https://github.com/jrathod9/Making-of-Space-X-/tree/master/Phase%203/Bullets)**
Location in repository : **\Phase 3\Bullets**

Moving on to the last thing that we will be doing in this phase. Make the aliens move. 
```js
Aliens[a].y += alienSpeed; 		//Add this inside the loop
								//where we use drawAlien();
```
So we have set the aliens in motion!:space_invader:

Final source code for this phase : **[Code Link](https://github.com/jrathod9/Making-of-Space-X-/tree/master/Phase%203/Final)**
Location in repository :  **\Phase 3\Final**

We are almost done with the game. This phase was about the aesthetics of the game. Next phase will be the final phase where we will add the **game logic** and a final touch with a good **background** and a visible **healthbar**.
Do leave comments/suggestions if any.
Cheers!:beer:

####  Play the game : 
- [With image sprites](https://jrathod9.github.io/Space-X/)
- [With self made sprites](https://codepen.io/jrathod9/full/jXwMWQ)

**[Star](https://github.com/jrathod9/Space-X):star:** this game!

<hr>

*Written by* : **Jay Rathod**:computer:
*Links* : [Portfolio](https://jrathod9.github.io/) | [Github](https://github.com/jrathod9) | [Codepen](https://codepen.io/jrathod9) | [Linkedin](https://www.linkedin.com/in/jrathod9/) | [Instagram](https://www.instagram.com/they_say_j/)