DEV Community

Jay Rathod
Jay Rathod

Posted on

HTML Canvas Games from Scratch #3


Hey devs!🎮
So we are all set to begin creating the game👾.
Let's do it!💥

Phase 3

Before we jump into coding, let us plan things.
Objects we will need :

  • Player (The space shuttle)🚀
  • Alien👾
  • Bullets🔫

Let us define these objects :

//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();
Enter fullscreen mode Exit fullscreen mode

Other variables that we will need to define are :

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
Enter fullscreen mode Exit fullscreen mode

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
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 :

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)

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;
}        
Enter fullscreen mode Exit fullscreen mode

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 :

//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;
    }
Enter fullscreen mode Exit fullscreen mode

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 :

Here's the source code : Code link
Location in repository : \Phase 3\MovingShuttle

Now let us fill the array of aliens:

//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
}
Enter fullscreen mode Exit fullscreen mode

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:

for(a = 0 ; a < Aliens.length ; a++)
        drawAlien(Aliens[a]);
Enter fullscreen mode Exit fullscreen mode

Result :

Here's the source code : Code Link
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.

 function keysReleased(e) {
     if(e.keyCode==32){             //keycode of spacebar
            var temp = new bullet(player.x , player.y - midBottomh - cannonh);
            totalBullets++;
            Bullets.push(temp);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let us draw all the bullets on the canvas;

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();
}
Enter fullscreen mode Exit fullscreen mode

Last but not the least lets draw these bullets on the canvas and make them move . This should be added inside draw():

//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]);
}   
Enter fullscreen mode Exit fullscreen mode

Result :

Here's the source code : Code link
Location in repository : \Phase 3\Bullets

Moving on to the last thing that we will be doing in this phase. Make the aliens move.

Aliens[a].y += alienSpeed;      //Add this inside the loop
                                //where we use drawAlien();
Enter fullscreen mode Exit fullscreen mode

So we have set the aliens in motion!👾

Final source code for this phase : Code Link
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!🍺

Play the game :

Star this game!


Written by : Jay Rathod💻
Links : Portfolio | Github | Codepen | Linkedin | Instagram

Top comments (0)