Create Your First JavaScript Game - Introduction to JavaScript Game Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Hi, I just have finished your tutorial :)

Your explanations are very clear and it was easy for me to follow the steps.

I've just had a problem with the order of some items. I had to place the 2 lines (document.body.addEventListener...) AFTER the 2 functions (keyUp and keyDown), otherwise the canvas was disappearing.

In your video, you have not this problem of order and I don't know why.

Maybe it is because I declare my functions like this : const x =() =>{

and yours are declared like this : function x () {

Anyways thanks for the video !

👍︎︎ 1 👤︎︎ u/Maleficent-Shoe-121 📅︎︎ Nov 13 2020 🗫︎ replies
Captions
today we're going to be creating a simple javascript game we're not going to be using any frameworks or game engines this is going to be 100 javascript as you can see we have a circle on the screen and i'm controlling it using my keyboard i can move left right up down and we even detect the edge of the screen and stop our little green blob this will be a great introduction to some simple game mechanics such as taking input from the keyboard detecting the edge of the screen and last but not least the game loop which continuously draws our screen using the skills that we learn in this video and my upcoming videos i plan to create tutorials for both pacman tetris and snake if you want to see more of these videos please subscribe like and share to get started with this project all we're going to need is an empty folder if you're comfortable using the command prompt you can go ahead and create a brand new directory by doing mkdir which creates a directory and name it green blob or any other name that you want then once you're ready and if you have visual studio code you can go ahead and do code dot once you're inside the directory that you want to be using this directory i currently have right here just to show you is empty all i have to do is type go dot hit enter and then i'm in my development environment to get started all we're going to need is two files within visual studio code over here i'm just going to add two files one is index.html and the other file is going to be our javascript index.js inside of our index.html file let's go ahead and create the default document template now really simple in visual studio code hit exclamation and then tab and that will create our default document layout i'm zoomed in a little too far there there we are and as you can see it created our default document layout you can hit tab tab tab and then we're inside the body now from the layout that we're building previously we have a title up here so let's add that real quick green blob now while we're working in this environment we want to see the screen constantly refreshing in order to do that i'm going to be using an extension called live server now you can install it simply by going over here on the extensions tab typing in live server installing live server click install then if we go back to our application and just right click on index.html and click on open with live server that will then open up our application over here and there we are we have green blob to make this easier for us to see i'm going to take this url over here and put it beside the editor now with live server installed the neat thing is that if i make any changes in my index.html over here like green blobs and click save my window will automatically refresh with those changes this is going to be great while you're developing the key piece to the game that we're going to be developing is the canvas the canvas element will allow us to draw to the screen and this is what we're going to be doing so go ahead and create a canvas element and i'll zoom that in so it's easier to see and i'll remove the window here on the side just by clicking there and hide or show that window with that hidden we'll have a little bit more room to work here and we're going to set our canvas aim id to the game area we'll give it a height and a width so our width will be equal to 800 and our height will be equal to 600 since our canvas is empty we're not going to see anything on the screen just yet next we'll go ahead and reference our script file over here so we're going to reference the script file and now the script file is just beside our document so we can say index.js and script tags need to have a closing tag like that now to test that this is working we can open up our developer tools and go to more tools go to developer tools then over make sure that you have console selected then what we're going to do is go into our index.js so close that go to index.js and we're just print out a hello over here just to double check that we're in a good known state and there you go we have hello printing on the screen so now we know that our html and javascript file are both working perfectly fine quick tip as well you can move around your console window over here your developer tools just by clicking on the three dots and then picking the layout that you want make this more readable i'm just going to move it to the bottom when we need it so in order to get our game going we're going to do two things first we're going to jump into the index.js over here and what we're going to do is we're going to get a reference to the game area that canvas that's what we're going to be drawing to this entire time so in the console.log over here we can remove the hello and then the very first thing we're going to want to do is get a reference to our canvas so over here constant canvas is equal to document dot get element by id and then remember the name of our canvas is game area the identifier pass that identifier in over here in order to draw on the canvas we need to get something called a context there are several different contexts 2d 3d and what we're going to want to do for our simple little game this little blob that we have here is we just want a 2d context because we're only drawing in two dimensions so canvas.getcontext will get us our context and we just have to tell it the type of context so we're going for a 2d context and then one quick simple thing that we can do for the beginning of our game over here just to play around and get comfortable with this canvas little typo there so you can see my by having this open i can see any typos that i make and i just made a typo here it says c-a-v-a-s is not defined so d-a-n because i just made a typo and then we're good to go benefit of having this open over here is that i can see any errors that i make while i'm developing so let's fill our background with the color black to begin with in order to do that we're going to take our context which we're going to use for our drawing we're going to tell it the color that it's going to draw to the screen with so we're going to say black and then we're going to tell it to draw a rectangle to the screen you're going to give it the x starting position which starts from the corner of the box that we're going to draw and then the width which we're going to get actually from the canvas itself because remember on the html element that we set outside here we actually set a width and a height we're going to grab those values from there so canvas.width and canvas dot height click save and then it fills our canvas over here with those colors i'll zoom that out so we can see that a little bit better and there we are so we have our canvas on the screen and it's with the color black and all we've done so far is decide a color and then fill that background i can make that a different color if i wanted to and our canvas will change colors to make this project just a little bit more fun instead of developing with this white background and this black canvas let's first just add a tiny bit of styling to give this cool background effect and this different text font that we have over here so in order to do that we're going to jump quickly back to our index.html you can see for game development you have very minimal html at least for this type of game when you're drawing to a canvas so first thing that we're going to do is we're just going to go ahead and just kind of put our styles in the document you could put this in a separate file but this project is so simple it doesn't really warrant having a separate css file first things first let's go ahead and style our game area now it may be hard to tell but i do have a green border around this and it's a little bit easier to see when it's zoomed in like that we're going to do is we're going to add a green border around that box so the game area is our canvas and all we're going to do is border 4 pixels solid green then you'll see a green little border around our box here next let's go apply this cool color effect on our background so no it's not an image it's actually something called a gradient and it just goes from one color to another color there are a lot of websites that will help you create gradients if you're not really up to doing that yourself so all we're going to do is add a background like this and then i'm just going to paste this in because i actually generated this on another website and i'll link that below in the description and that's it you tell your background you give it a linear gradient you give it the starting degrees i believe and then the color that you transitioned from and the percentage and how that works a lot of websites will help you generate this for you give you visual aids to create it for you and you can just create your own effects next the other thing we have too is our green blobs text over here is align center so let's go ahead and just align center now everything on our page is aligned or game area plus the text and one last thing that i want to do is i want to protect against scroll bars appearing as they can affect our keyboard input as we move our blob up and down on the screen so we're just going to set overflow to hidden which will hide our scroll bars so just like that we're going to hide roll bars and then our h1 if you've noticed our text over here in our h1 looks like this it's just the default text that you get and our text over here is slightly different so we're just going to use something called comic sans but we're going to go ahead at that font family to comic sans ms and if i hit save you'll see that text changes figured comic sans would be a little bit more appropriate for a game and that's it that's all the styling that we have just a tiny bit and that's it that's all the styling that we have for our game just a little bit of the game area a little bit of the body and a little bit of the h1 now we can get back to our game development back in our index.js what we're going to do is we're going to create a function that we're going to call draw game we'll go ahead and create a function called draw game doesn't take any parameters in and we're going to take that code that we have over here called the that fills the black background over here that we have we're going to create another function called clear screen below that then we're going to just going to take that little bit of code and put it inside clear screen now once we do that clear screen is not being executed so inside of draw a game execute clear screen and then at the very end the last thing that we want to do is we call draw game draw game is going to first thing it's going to do is just clear the screen which creates our background color that we have over here at the beginning of this video i mentioned that there's going to be a game loop well this is going to be our game loop over here the draw game it's not a game loop yet but we'll be getting to that shortly after we've cleared the screen next we want to draw our little green blob let's create a function called draw green blob and then we're just gonna call the function there and we'll make a function called draw green blob like that inside draw green blob what we need to do is go ahead and draw our little little green blob here now that green blob is green and it's a circle so in order to do that we're going to be using our ctx over here our context our 2d context originally when we drew the background over here clear screen we set fill style to black now we're going to set the fill style equal to green and in order to draw a circle what we need to do is we need to give it a begin path we need to say that you're going to begin your drawing here then what you're going to do is you're going to draw an arc so this is where we actually draw the circle now we need to give this an x position and a y position now those things are going to be changing as we use the keyboard to change the position of our green blob we also need to give it a radius so let's also define a variable now these variables aren't defined yet so i'm just doing these down here and then we're going to define them up here then we need to give it a starting angle right there and an end angle simply for the end angle all we need to do is math dot pi times two then what we're going to do is we're going to define our let x is equal to 100 let y equal to 100 and then we also need a radius so we're going to say const radius we'll make it a let just in case we want to change that later let radius equal to 50 then save that and the last thing that we need to do after we define the arc that we want to create the circle is we need to tell the context to fill that circle in so we call ctx dot fill and then we have a circle on the screen as you can see the circle is positioned at x position 100 so x and y start from this very corner over here x and y are zero so increases as you go right so this is 100 position and y increases as you go down so if we take our y and we make that 400 you'll see that our circle is now further down on the screen if we increase our x and we make that 550 or no i will go if we make it that number it'll go way off the screen but if you make it 500 it'll go over this way remember all positioning x and y starts from the corner over here before we can start taking any keyboard input to start moving our blob around on the screen we're gonna have to make sure that we have a game loop what does a game loop do well a game loop runs every number of seconds in order to update the screen the game loop will run 60 times a second in order to redraw our screen over here 60 times a second normally this matches up with your monitor refresh rate two different ways of doing this are something with something called a request animation frame where you can ask javascript hey the next time you're ready to repaint that screen or redraw that screen execute this particular function and you just give it a function that you pass in other way of doing it is by using set interval with set interval you give it a function for example draw game and then you give it the interval in which you want this to run and this is taken in milliseconds so 1000 milliseconds would mean that i would run draw game every one second in order to be a proper game and make the screen look really nice while you're doing this is you want to draw your game in sync with the number of times that your monitor refreshes you generally don't need to think about this but most monitors are 60 60 hertz which means that your screen be drawn 60 times every one second let's take a look at how these two different functions work so right now in our draw game if i do a console.log and i say draw and click save you'll see that draw is only called once but if i call request animation frame and with this particular setup that we have right here recall that we have draw game here at the bottom so we're doing that initial execution there then what we're going to do is request animation frame we're going to say call well the same function draw a game and what this will cause is a loop and you can see that this number over here in my console is increasing continuously so the screen is being redrawn and this will be great because once we're taking keyboard input our character will move across the screen and be redrawn all the time so the way this works just to recap is draw game is called at the end then when we're executing draw game we go ahead and say view it up say request animation frame as soon as you're ready go ahead and recall draw a game so this ends ends up going in a continuous loop and that's why we see draw being called over and over and over the alternative way to doing this is using set interval so to use set interval we don't need to call a draw game at the end over here like this what we need to do instead i'm going to remove request animation frame and instead of calling draw game all we have to do is say set interval and then say which function we're going to use we're going to use draw game we're going to call it every 1000 seconds and to match my monitor's refresh rate which is 60 hertz i'm going to divide by 60 so it gets called 60 times a second click save and you can see we get the same result it just keeps drawing the screen over and over and you'll see how useful this is once we start taking keyboard input before we continue let's actually use request animation frame i'm going to put request animation frame back in i'll remove these comments that we're not using and at the bottom of the screen i'll delete line 28 and put back line 27 so just to recap for request animation frame we execute draw game at the very end of our of our file over here and then we call request animation frame over here which will queue up to draw the next screen when it's ready at the same time we'll also remove that console.log so we can see that it's working now let's get our character moving on the screen the first direction that we're going to get our character to move is down so we're going to set down pressed equal to false so what we're going to be doing is we're going to be listening to the keyboard so if you're pushing down on the down key we're going to say down pressed is equal to true once you let go of that key and the key goes up we're going to say it's equal to false the way we're going to achieve this is using two events key up and key down for the key down event we're going to set it up as follows here in the bottom of our file over here we're just going to use document dot body dot add event listener and the event listener that we're going to add is key down all lower case like that and then we need to give it a function to execute we're also going to be listening to the document dot body dot add event listener we're going to listen to key up and also give that a function called key up we haven't created the keydown and key up function so we get this error over here then we'll define those two functions e down as follows which will take in an event and we'll define also the key up which also takes in an event let's implement that key down event inside the keydown event over here what we're going to do is we're going to detect if the current key is the down key so if the event dot key code is equal to or equal equal to 40 then down pressed is going to be equal to true okay so what is an event and what's a key code the event over here is what gets passed into the key down event that event will contain information about the key that it's responding to the key that's responding to when i push down will have a code now every single key on your keyboard has a code and the down will have key code 40. now how did i know that well one is i could use console.log in order to print that on the screen but i also just googled it it's easy enough to google and check what the key codes are for all the keys for example over here i have googled javascript keycode arrow keys and as you can see i can find that the down key over here is number 40. the other keys that we're going to be using are also here too as well for left up and right now that we have this key code over here when you push it down on the down key we're gonna say down pressed is equal to true that means that we need to change our y position if it's a hundred we're gonna want our character to move down the screen we can increment by one we can remember by 10 we can increment by different numbers the way that we're going to do that is before we draw our green blob is we're going to make a function called inputs and inputs will respond to the different key presses so let's go ahead and define inputs then over here we're going to create a function called inputs and inside inputs we're going to do is we're going to say if down pressed is equal to true then we're going to say y is equal to y plus 10. so now when i push down on my keyboard our character moves down now i pushed that key once and the character continued to move down the screen the reason for that is down pressed was always true remember we registered key down and we said down pressed equals true well we didn't do the opposite of that which is we need to detect when the key is let go of in order to do that all we have to do is copy and paste what we have inside our key down events put that inside our key up then set down pressed to false save that go back to our game and push down now our character moves a little bit at a time now that we can move our character in the down direction let's get the rest of those directions done as well so we're going to add a few more events over here i'm going to say let up pressed equal to false then we'll do let left pressed equal to false and then let right pressed equal to false then we're going to do is implement our inputs over here and now i don't want to have to put 10 all the time because i might want to change that number in the future we're going to define another variable called speed i'll make that equal to 10 for now and then over here i'll say let y equal to y plus speed so we can change the speed of our character movement if we wanted to you see if i make this one and save it and now click down you can see i moved just a tiny bit at a time if i make this one t it moves a lot quicker on the screen so we're going to keep that at 10 because it seems to be a good speed but we'll go ahead over here and i'm going to try and keep these all in same order so we're going up down left right so over here i'm going to do our up now to do our up what we're going to want to do is another up if statement we're going to say if up pressed what we're going to do because our y so for down we're increasing the y for up we want to decrease the y so let's say y is equal to y minus speed now you can also write this as y minus equals feet and that will do exactly the same thing as this line up here but we'll stick with this one for now so there you go now this still isn't going to work just yet so i'm going to implement the right and the left let's go left rest now for left we're going x so that means when we go this way on the screen you know going left we're going to go negative so x now the x position is going to be x minus speed and save that then if right is pressed well right is going to be x which is positive going this way so x is equal to x plus speed with all of our inputs over here handled up down left right pressed now we just implement the keyboard events over here so we've done the down and now we're going to go the same order we did before so we're going to have up so if the event dot key code is going to be equal to the up key code which is 38 then what we're going to do is we're going to say that up is being pressed and we're going to set that to true then just to speed things up i'm going to copy the down over here and i'm just going to put left or there and then if the left key code which is equal to 37 remember these you can just google so left pressed is equal to true and then just take that again and copy it and put right and then if right is pressed we'll set that to true and the right pressed key code is equal to 39 here you go so the only thing we haven't implemented is the up and this is pretty simple i am going to just copy and paste this whole thing that's inside key down and do the opposite a little bit of an anti-pattern here because these are very similar except for which value gets changed but that could be fixed in a refactoring now it's really cool right here if you're in visual studio code and you highlight the word true and you hit control d on windows or command d as you can see i can highlight every time i click it it highlights the next row so now this one's going to be highlighted and now i have four different cursors that entire thing is highlighted i can just type false and it types false in every single one of those so now that we've set up our variables at the top for the pressed we've implemented the inputs to change the various speeds or the various positions for y and x and then we've also handled the keyboard events now when i go back to our project over here i can go down up left and right and because we implemented the speed being the same for all the positions i can also change that speed if i wanted to and make it faster if i wanted to and then i can move even faster on the screen and as you can see i even can move in a diagonal position because it's detecting when left and right are pushed together and our circle will move in a diagonal let's put that back to 10 as it's more manageable if we come back over here you can see that diagonal as i can move in the last thing that we need to do is check the boundary so our little green blob over here can go right off the screen and we don't want our green blob wandering away so let's do a boundary check to do a boundary check we're going to check you know if you're hitting the top of the screen and going out and the same for the left right and down so in order to do that right after we've updated our inputs we're going to check that all those inputs are valid so over here we'll create a function called boundary check go ahead and create your boundary check and then inside the boundary check let's check that up boundary first the way we're going to do that is we know the radius of our circle and we're going to say if y is less than the radius of our circle reset the y position equal to the radius now if i try and move my circle he can't no matter how much speed he gains he can never go beyond the top position over here can't exit the top part of the screen now let's just say that i played around with these numbers and i did minus 10 here and minus 10 here minus 10 you'll see that our circle will well let's let's do a higher number there let's do 40 and 40. so now you can see my circle gets cut off in order to prevent my circle from being cut off i do y is less than the radius and then set it back to that number so even if behind the scenes my circle disappears behind there we just reset him to this position over here now let's check the down position i'm going to put a comment over here that that's up and then we'll do the down right there and we're going to say if the y is greater than our canvas dot height so let's give that a try let's see what happens what this effect is if we do it then we'll say y is equal to canvas.height if i exceed the canvas height let's try that and see half our circle goes away well in order to fix that we know that radius is half the circle so we'll do radius we'll do height minus radius and height minus radius over here to reset you back so that if that happens then you can't go through the bottom to block our little green blob from going over the left side we're going to do the x position because now we're on the x left and right we'll do x is less than radius which is just like our up over there but on the x plane then we'll say x is equal to radius right now i can go through but click save now i can't go through can't go to the top can go through the sides now what about our right side well right side is going to be kind of like the down so we'll put a comment there for left and then for the right over there we'll say if the x is greater than canvas dot width minus the radius then we can say x is equal to and we can just copy and paste that there now when our little green blob moves can't go beyond that area and now we've implemented exactly the same game that we had at the beginning of this tutorial same color same css and same functionality over here where i can move my circle around and i can't escape the various this little box that our green blob is contained within the cool thing with a little game like this that we've made is that we have all these variables now that we can play with we can add more key presses and do different things we can increase the size of our circle if we wanted to because we use these variables and not hard coded numbers we could make our circle a lot bigger but also once our circle's a lot bigger we still can't exit the screen because we use the radius in our calculations in the boundary check so no matter how small or how big we make this circle it can never escape now that's a really tiny circle there but it can't escape outside of our boundary so go ahead once you've done this tutorial it's fun to play with these numbers and see what you can do you can definitely do some really cool things one just feels incredibly slow pen feels more smooth with the movement of our little green blob as i mentioned you can do some pretty cool things with these variables and get really creative so let's try one creative thing here in the draw green blob what we're going to do is change the color depending on the direction that you're going so if you are going up let's change that color so the default style will be green we'll put that at the top and then if up is pressed what we're going to do is change that color there we go change that color so i'm just going to copy that style and we'll change that to red and then we'll just copy this over here and we'll say if down is pressed what we'll do is we'll change the color to blue and then if left is pressed we'll make the color yellow and then for right make sure we got our spacing good here it's going to put them all together like that and then the last one that we need to do is right we have red blue yellow and we'll do purple so let's go ahead and try that out as you can see the blob is still green so this code over here is being executed well it stays still and no buttons are being pushed once i move and i move right it's purple i move left is yellow if i move up it's red which looks really really cool on the screen as we move our character around so there's just a little bit of creativity that you can add to your game and you can change it around just by playing around with the variables and changing how it behaves you can get these really cool effects i challenge you to try and create something creative using some of the game mechanics that you've learned here in addition to react and javascript i plan to make more videos about creating games in javascript i look forward to creating tutorials on pacman tetris snake and other smaller videos about various gaming mechanics if you'd like to see more of these videos please subscribe like and share [Music] you
Info
Channel: Coding With Adam
Views: 17,582
Rating: undefined out of 5
Keywords: Game development, game development in javascript, javascript, jS, game loop, canvas games, javascript canvas game, simple javascript game, simple game, move on canvas, js game, simple canvas game, javascript game introduction, introduction to game development, game dev introduction, javascript game, javascript games, games with javascript, edge of screen detection, game development intro, in
Id: UUFPEgRKwf4
Channel Id: undefined
Length: 36min 43sec (2203 seconds)
Published: Sat Oct 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.