How to create a simple gameloop for your JavaScript games in under five minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this session we are going to show you how to create a simple game loop for your javascript games in under five minutes and if you stick around to the end we'll show you how to make an object move around the screen my name is david and i publish videos like this every monday let's get started so the first thing we need is two files for our project we need an html file to display our content and a js file for our code now that we've created the files we'll open up our index.html file and add the html layout so let's vim into our project so all we really need here is a basic html page so i'll paste in the code and the only real line of importance here is line 4 which creates a reference to our javascript file next we'll open up our javascript file and create an onload function to create an onload function we do window.onload equals function and for now inside that function we'll add a simple console.log message our onload function will be triggered when our html page is loaded we can prove that by opening up our html page and displaying the browser's console terminal so let's do that next oops we've got an error what is that turns out someone can't spell function properly so let's fix that and now when we refresh our page we'll see the console message that we added to our onload function thus proving that our onload function is triggered when the page is loaded so the next thing we need to do is create a function called update so let's go back to our js file and add that so we'll do function update and for now we'll add a simple console.log output to that function as well next we'll create another function called render function render and once again we'll add a simple console.log output here too these two functions update and render also very basic for the moment are the key ingredients for any game loop to understand why we need to quickly discuss how animation works so let's imagine a simple animation where we want to mimic a ball moving across our screen firstly we have to specify where on the screen we want to draw the ball and secondly we need to draw the ball at the specified location in short we need to update the ball's position and then render it on the screen then we would repeat the update render process but this time we would modify the location of the ball before we rendered it again thus when we re-rendered the ball it would be in a new location and thus looked like it moved we would continue this process until our ball moved off the screen furthermore to make that update render process look like an animation we need to carry out the update and render process so fast that the human eye doesn't see the rendering just the motion and that magic number is 30 times per second that's right we need to update and render the ball 30 times per second in order to trick the human eye into believing that the ball is actually moving this is how animation works it's how movies work and it's how games work and in gaming the mechanism that produces this animation is called the game loop so let's create that now so firstly let's create a variable called loop then we'll create another variable called fps and set it to 60. fps stands for frames per second think of a frame as one iteration of the update render process and as i mentioned before we only need to do that update 30 times per second however 60 times per second is smoother and it's not 1995 so your browser can handle it which is why we're setting our fps variable to 60. so now that we have our relevant variables in place we're going to go ahead and create our game loop that game loop is going to live inside our onload function so we'll do loop equals set interval then we'll create an anonymous function and inside that anonymous function we'll add update and render and finally we'll add 1000 divided by fps and then we'll close off our set interval function so let's go over what we did here so firstly we've set our loop variable to a function called set interval set interval is a javascript function that invokes a specified function at a specified interval it does that by accepting two parameters the first parameter is the function that we want to invoke the second parameter is the interval between invocation of the aforementioned function in our case we've passed an anonymous function that triggers our update and render functions and our second parameter is 1000 divided by our variable fps 1000 equals 1000 nanoseconds which translates to one second that value is divided by our fbs variable which is of course 60. in short we've set our interval to one second divided by 60. this means that we'll invoke our anonymous function approximately every 16.6 nanoseconds which surprise surprise is approximately 60 times per second on a side note we don't need to assign the set interval function to our loop variable but doing so allows us to end the loop if we so wish this is obviously quite useful when the game is considered over at that point there is no reason to continue running the loop so now when we load our html page and view the browser's console terminal you will see the console go absolutely bananas as it prints update rendering messages every 16.6 nanoseconds and that is essentially our simple game loop however printing messages in the browser's console is a pretty poor example of a game loop so as a bonus let's create an animation of a ball moving around the screen so let's head back to our index.js page so the first thing we'll need is a canvas to draw on so let's open up our html page and inside the body tag we'll add our canvas now that we have our canvas on the screen let's go back to our index.js file and create variables that we can use to set a reference to the canvas and the canvas's context object so we'll do let cmv that will represent the canvas and ctx will represent the canvas's context object then we'll create a new function called prepare canvas so we'll do function prepare canvas and inside that function we'll set references to our cnv and ctx variables cmv equals document dot get element by id and we'll pass through the canvas object's id which is cmv and now that we have that reference to the canvas we can use that to set the context object ctx equals cmv dot get context and we want a two dimensional context so we pass through the string 2d like so the next thing we'll do is remove the padding and margin from the html page so we do document dot body dot style dot padding equals zero and we do document dot body dot style dot margin equals zero and now that we have the pattern and margin sorted we'll set the size of our canvas to that of our html page so we do cmv dot width equals window dot inner width and cmv dot height equals window dot inner height like so and finally we'll add the prepare canvas function to our onload function prepare canvas so now that our canvas is prepared let's color the background to do that we'll create a function called fill canvas in this function on line 15 we are setting the color that we want to use and then on line 16 we're using fill rect to draw a rectangle over the entire canvas thus effectively filling the whole canvas with our specified color to trigger this function we need to call our fill canvas function inside our render function and we simply add fill canvas here and when we reload our page we will have a nice calming blue background so now that we have a canvas and a nice calming blue background let's create a ball that we can move around the screen so we'll need a new object called ball and inside that object we'll create four properties one for the x position one for the y position one for the size and one for the color then we want to add a draw function to our ball object i'll paste that in and quickly go over what it does so our draw function simply accepts our context object as a parameter and then uses that context object to draw a circle on the canvas i don't want to make this a canvas api tutorial but line 10 sets the color line 11 sets the path which is something you need to do before you draw a circle line 12 calls the arc function which draws the circle and then line 13 fills that arc so with the draw function in place the next thing we need to do is call our ball draw function in our render function as follows and when we reload our html page we'll see the ball partially hidden in the top left corner of the screen so that's kind of cool but it's not what we want so let's fix that now so firstly we want the ball in the middle of the page and secondly we want it to move let's deal with the positioning first we'll give the ball object another function called init it will accept the canvas as a parameter then inside that function we'll use the canvas object to position our ball in the middle of the screen all we're really doing on line 10 and 11 is using the canvas and the ball dimensions to set both the x and y positions to the center spot on the screen and now we'll call the ball a net function before we run our game loop and this time when we reload our page we'll see our ball in the middle of the screen but we're still not there because our ball is not moving let's change that now so let's create another function for our ball object called update we'll also add some new variables for velocity and then inside our new update function we'll add the following code line 16 and 17 simply updates the position to its current position plus the value of the velocity and finally we'll need to add the ball update function to our game loop update function and let's get rid of this console message and while we're at it we'll get rid of the one inside render too and now when we reload our page our ball moves off the screen refreshing the page will repeat the animation and that is how a game loop works you call your object update function in your game loop update function and you also call your object's render function and your game loops render function but as an extra bonus let's add some collision detection so our ball remains within the boundaries of the screen so the first thing that we want to do is pass the canvas object through to our ball update function like so then we want to update our call to the ball update function in the game loop update function after that we want to create a new function in our ball object called check for collisions and inside that new function we want to add the following code so this is not a tutorial about collision detection but basically the code we just added checks to see if our ball is collided with the left right top or bottom of the screen if it detects a collision with any of the boundaries it changes the direction of the ball i.e if it hits the left side of the screen then the ball moves right if it hits the top of the screen then the ball moves down etc etc now that we have the check for collision code in place we want to call our new function and the ball's update function and we'll do that below line 17 like so finally when we reload our page the ball will bounce off the screen forever more and that is how you create a simple game loop so the purists out there will tell you that this game loop that you see on line 40 is not deterministic i.e the game loop will perform differently on different machines and i'm not here to argue with the purists because in all honesty they're correct this isn't the best game loop if you're making a commercial product however if you're just starting on your web game development journey then this game loop will serve you well during your initial projects and it will also allow you to move on to more interesting problems that you'll also need to overcome before you can produce your first full working javascript game also the loop takes advantage of javascript's set interval function which has obviously been developed to perform on a wide range of machines and browsers thus you can sleep safely at night knowing that the mozilla developers have most likely developed an interval function that is capable of handling your version of pong on varying machines and that my friends is that if you found the content useful then consider hitting the like button and subscribing to the channel also if you like web games then check out my nova project where i am currently creating a web clone of the 90s macintosh game escape velocity i also have other tutorials that show you how to draw on the canvas api resize the canvas programmatically and a series of videos on how to use canvas api to create games i also do other videos related to programming videos are published every monday and last but not least thanks for watching you
Info
Channel: David Reid
Views: 47
Rating: undefined out of 5
Keywords: How to create a simple gameloop for your JavaScript games in under five minutes, how to create a gameloop for your javascript games, javascript gameloop, create a javascript gameloop, javascript games, code a javascript gameloop, how to create a javascript gameloop, javascript gameloop tutorial, david reid, code a web games gameloop, how to create a gameloop for your web games, how to code a gameloop for your web games, web games gameloop, canvas api javascript gameloop
Id: QXYT8sEJRZk
Channel Id: undefined
Length: 15min 0sec (900 seconds)
Published: Mon Nov 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.