JavaScript 2D Game Tutorial

Who says learning JavaScript cannot be fun. Let’s take another step towards Front End Web Development mastery and practice fundamental programming principles and techniques in this vanilla JavaScript 2D game tutorial.

Some people skip my generative art and HTML canvas animation videos and just focus on game tutorials, but I want to show you that all canvas techniques I teach can improve your games, if you get creative with it.

Relevant links:
Sprite sheets and game art: https://www.gamedeveloperstudio.com/

This tutorial is part of a series, for more game development with pure vanilla JavaScript check out this playlist https://www.youtube.com/playlist?list=PLYElE_rzEw_sowQGjRdvwh9eAEt62d_Eu

The main reason that people don’t succeed in becoming a self-taught Front End Web Developer is because they loose motivation. My tutorials focus on teaching you everything you need to know about HTML, CSS, JavaScript and HTML5 canvas element, while at the same time building fun, visual and memorable projects.

In today’s vanilla JavaScript 2D game tutorial I will show you how to add sound to your games, how to make player character follow the mouse whenever we click somewhere, how to handle simple collision detection that triggers sprite animation and how to rotate our fish sprite correctly to face the direction the player is moving. We will also cover repeating backgrounds, how to handle score and couple of other things. First we will build a solid good quality game skeleton that can be used for more than just this particular fish game. Then we will start adding graphics with sprites, particle effects and make the game look polished and clean.

I made a tutorial on how to rotate elements with vanilla JavaScript on HTML canvas for beginners recently (https://youtu.be/TBXjWsR7XDA). Today we will use the same technique to rotate player character around, and we will build on it and take it to the next level by making it face mouse and move towards it.

You can message me on TWITTER https://twitter.com/code_laboratory
Check out some of my source code on CODEPEN https://codepen.io/franksLaboratory

If you started with vanilla JavaScript and HTML canvas recently you might want to try some of the tutorials from beginner friendly projects playlist first: https://www.youtube.com/playlist?list=PLYElE_rzEw_v8TXJ_ITSSBP_ypUKfQ7K-

To become a professional Front End Web Developer, you need to practice and work on your skills, these are some of my favourite well structured courses that cover everything you need to know:
JavaScript Beginner Bootcamp (2020) https://bit.ly/3aqFFhc
20 Web Projects With Vanilla JavaScript https://bit.ly/3anlCQR
Learn SVG Animation – With HTML, CSS & JavaScript https://bit.ly/2PRGwOr
HTML, CSS, JavaScript – Build 6 Creative Projects https://bit.ly/33YIBjT
Object-oriented Programming in JavaScript https://bit.ly/3f4Otu0
How to Program Games: Tile Classics in JS for HTML5 Canvas https://bit.ly/2ZUfKuG
Next Level CSS Creative Hover & Animation Effects https://bit.ly/3jEkzju
The Web Developer Bootcamp (Older but still very relevant) https://bit.ly/2ZZJM0d
Modern HTML & CSS From The Beginning (Including Sass) https://bit.ly/2Ec6Cch
Advanced CSS and Sass: Flexbox, Grid, Animations and More! https://bit.ly/3g0uqxT
JavaScript Basics for Beginners https://bit.ly/32Tn5wq
JavaScript: Understanding the Weird Parts https://bit.ly/2WVe0zn
The Complete JavaScript Course 2020: Build Real Projects! https://bit.ly/3fXGwaZ
Modern JavaScript From The Beginning https://bit.ly/3fWJgWk

#javascript #htmlcanvas #frankslaboratory
Music: (YouTube audio library) Vacay In Fiji Riddim – Konrad OldMoney, World Map – Jason Farnham

The description of this video may contain affiliate links, which means that if you buy one of the products that I recommend, I’ll receive a small commission without any additional cost for you. This helps to support the channel and allows me to continue making videos like this. Thank you for the support!

source by Franks laboratory

javascript

Mourad ELGORMA

Fondateur de summarynetworks, passionné des nouvelles technologies et des métiers de Réseautique , Master en réseaux et système de télécommunications. ,j’ai affaire à Pascal, Delphi, Java, MATLAB, php …Connaissance du protocole TCP / IP, des applications Ethernet, des WLAN …Planification, installation et dépannage de problèmes de réseau informatique……Installez, configurez et dépannez les périphériques Cisco IOS. Surveillez les performances du réseau et isolez les défaillances du réseau. VLANs, protocoles de routage (RIPv2, EIGRP, OSPF.)…..Manipuler des systèmes embarqués (matériel et logiciel ex: Beaglebone Black)…Linux (Ubuntu, kali, serveur Mandriva Fedora, …). Microsoft (Windows, Windows Server 2003). ……Paquet tracer, GNS3, VMware Workstation, Virtual Box, Filezilla (client / serveur), EasyPhp, serveur Wamp,Le système de gestion WORDPRESS………Installation des caméras de surveillance ( technologie hikvision DVR………..). ,

46 réflexions sur “JavaScript 2D Game Tutorial

  • juin 23, 2021 à 9:54
    Permalien

    Hi Frank. Just getting started with your videos in my intermittent spare time and I love them. I've already completed two simple projects of yours, but I would like to know if this fish game will work on tablets.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Here is my code. Something weird is happening whenever I click on the canvas. After I press the mouse, the circle snaps to a random spot on the canvas. Can someone please help me? Thanks in advance for your assistance.

    //canvas setup
    const canvas = document.getElementById('canvas1');
    const ctx = canvas.getContext ('2d');
    canvas.width = 800;
    canvas.height = 500;

    let score = 0;
    let gameFrame = 0;
    ctx.font = '50px Georgia';

    //Mouse Interactivity
    let canvasPosition = canvas.getBoundingClientRect();

    const mouse = {
    x: canvas.width/2,
    y: canvas.height/2,
    click: false
    }
    canvas.addEventListener('mousedown', function(event){
    mouse.x = event.x – canvasPosition.left;
    mouse.y = event.y – canvasPosition.top;
    console.log(mouse.x, mouse.y);
    });
    canvas.addEventListener('mouseup', function(event){
    mouse.x = false;

    })

    //Player
    class Player{
    constructor(){
    this.x = canvas.width;
    this.y = canvas.height/2;
    this.radius = 25;
    this.angle = 0;
    this.frameX = 0;
    this.frameY = 0;
    this.frame = 0;
    this.spriteWidth = 498;
    this.spriteHeight = 327;
    }

    update(){
    const dx = this.x – mouse.x;
    const dy = this.y – mouse.y;
    if(mouse.x != this.x){
    this.x -= dx/30;
    }
    if(mouse.y != this.y){
    this.y -= dy/30;
    }
    }
    draw(){
    if (mouse.click) {
    ctx.lineWidth = .2;
    ctx.beginPath();
    ctx.moveTo(this.x, this.y);
    ctx.lineTo(mouse.x, mouse.y);
    ctx.stroke();
    }
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fill();
    ctx.closePath()
    }
    }
    const player = new Player();

    //Bubbles
    //Animation Loop
    function animate(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    player.update();
    player.draw();
    requestAnimationFrame(animate);
    }
    animate();

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    What If I want the bubbles to fall down instead of rise up? How do I make the bubbles fall down from the top?

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Hi, Frank!
    You could not only run loop backwards at 22.50, but also use while loop, it faster (not so much in this case, but a good practice) and also less code to type.
    for example
    let i = bubblesArray.length
    white(i–){
    //your code…
    }

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Wow! I wish you made this stuff 2 years ago when I started creating canvas games. Good explanations and good pace!!
    I know how to do this on my own but I subcribed anyway.
    But you really should apply clean code concepts to your code, like stop spaghetti code madness, redundant code and shifting classes into serparate files 😉

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    25.50 just call if check statement before updating and drawing
    if (bubblesArray[i].y < 0 – bubblesArray[i].radius * 2) {
    bubblesArray.splice(i, 1);
    }
    bubblesArray[i].update();
    bubblesArray[i].draw();

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Great tut. Quick question. My red sphere only moves horizontally on mouse click. I've gone over the code a ton of times but can't find my error. With that behaviour, can you point me in the right direction. Thanks.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Thank you so much Frank! I'm having an error on my script.js where class Player{ has an error of ',' expected.ts(1005). What do I do? Nothing is animating.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    New to your channel… love the content along with your clear cut explanation brother (: thanks

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    At 34:44 one of the bubbles didn't have a sound. I have the same problem. If I get the bubbles too fast after one another, 1 sound is not played. Can you help me how to fix this, please?

    edit: btw it's an amazing video, thank you so much for uploading <3 <3
    You are very inspirational.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Probably much too late but for the drawing-and-splicing-blinking issue, I think the problem is that since your 'i' is increasing even when you splice, the very next element doesn't get drawn. (you were drawing bubble 20, it's out of screen, you remove it, i++, now you are drawing the original bubble 22. The original bubble 21 is skipped).

    The obvious solution is to i– whenever you splice.
    The lazy solution for those who use foreach loop instead of for loop is to use
    setTimeOut(()=>{ bubbleArray.splice(i,1); });
    instead.
    I'll be honest I have no idea why this works, mostly because I don't know how js control flow works. My guess is that setTimeOut with no 2nd parameter will execute whenever you are between function calls or something? So it happens to work perfectly?

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    after making a game in JS how to convert it into apk and ios support file for an android, iPhone device so that we can upload in playstore,AppStore???

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    The blinking occurs because we are removing an object from the array which kinda cause holes to other array object during the animation the way to remove this is placing the splice function that is the area of code where we are removing the bubbles, place it in a setTimeout function and set the parameter which is when the function is to be executed to zero
    Like this
    for(let I=0; I<bubbles.length; I++){
    if(bubbles[I].y<0){
    setTimeout( ()=>{
    bubbles.splice(I,1);
    },0)

    }
    }

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    how to make it viable on smart phones, by touching the phone screen instead of mouse click?! thanks

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    instead of sending the bubbles straight upwards , is there a way I can send them diagonally from the bottom ? I think it'll use ctx.translate but I'm not able to execute it . Can someone help ?

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    hello 41:47 , I have problem with ctx.restore(); .. keeps saying SyntaxError: Unexpected token '.'. Expected a ';' following a class field. however can not see what I've done wrong. please help

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    hello I have the data of a game in .js that I download on the internet, I am new to this and I would like to know if there is a way to extract the files that this game contains (like the images).
    thank you and I hope you answer me 🙂

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Thanks Frank
    It was really helpful
    I am a beginner and I learned a lot from your videos
    Thanks!!!
    😄😄😄😄

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    hello frank, i want ask you something,how to fit the animation 100 %? cause i have problem with that,in my case my animation only fit 50 % in that bubble.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Hiii 🙂 So glad I found this channel. I have a dumb question which is that at 9:59, why is the x coordinate of the mouse canvas.width/2? Would be great if anyone can answer.

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    Hello. Im having a problem adding sound. When the collision happens i get an error in the console saying GET http://favicon.ico:17.0.0.1:5501/favicon.ico 404 (Not found).

    Then there is another:
    Uncaught (in promise) DOMException: The element has no supported sources.

    I maked sure all the sound files are spelled corectly and are in the right folder.

    Any help would be much appreciated. Thanks

    Répondre
  • juin 23, 2021 à 9:54
    Permalien

    What should I call this game: Bubble Popper? Click the LIKE please 😀 Is this your first JavaScript game or have you built any games before? How many and what type of game was it?

    Répondre

Laisser un commentaire