How To Create a JavaScript TileMap For a 2D Game

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

In this tutorial we learn how to build a 2D tile map for a game in JavaScript. We set up the basic architecture for a game and dive into the details of what a tile map is and how to build one.

👍︎︎ 1 👤︎︎ u/CodingWithAdam 📅︎︎ Aug 03 2021 🗫︎ replies
Captions
in this video we're gonna be building a tile map the tile map that we have here is for the game pacman a tile map lets you build a game level using a grid system this is a really common way to build a level for a 2d game the map that we have here is static in meaning that it doesn't scroll this particular map is made up of four images and each image is 32 by 32 pixels for example we have a dot pac-man a ghost and a wall to help illustrate the grid system i'm going to enable a feature that puts a yellow outline around each image now you can see the grid it's made of rows and columns contained in each cell is what we call a tile a tile represents a certain image for example this tile over here represents pac-man this one represents a dot putting the tiles together can sometimes make a larger image for example the walls the way they're drawn and the way they connect makes it look like a much larger image this square in the middle here looks like one gigantic wall even though it's made up of several different tiles if you enjoy my videos please subscribe like and share with that being said let's get to the code so i'm going to be using visual studio code over here and i got my chrome browser so we can see live updates of the code that we're writing we'll go ahead and create a brand new folder by clicking open and then what i'm going to do is find the folder where i want to create my games the previous games i've created are here i'll go ahead and click new folder and i'm just going to call this tile map and then click open let's start by setting up the files that we're going to need for application so first file we're going to add is our index.html we're also going to add a game.js we're going to add a tilemap if you'll notice it's capital because it's going to be a class and then we'll create a folder to store all the images that we have all four of those images let's go ahead and we're going to drag those images in that we're going to need so there's only four of them there's the ghost image the pacman the wall and the yellow dot you can find all these images in the complete project and i'll be linking that in the description next we're going to go ahead and implement our index.html really easy to do that in visual studio code just put an exclamation hit tab and then it makes all that html for you and i'm just going to minimize this over here so it's easier to see and we're just going to add some basic html that we need to make this tile map i'll go ahead and we'll add a div inside that div you can just put an h1 if you really want i'm just putting a title probably put pacman but i'm just going to put tilemap and then the canvas so this is where we're going to do all the all the drawing too and we're going to give that canvas an identifier and i'm just going to call it a game and that's all the html we really need aside from the script tag we're going to have the src and it's going to reference our game js and very important put type equals module because we'll be doing an import now that we have this basic html let's get it running inside our browser so we can see these changes as we code i have a really simple extension installed called live server i kind of recommend that you install that one it's really awesome every time you click save it'll update over here i've installed that and once you have it installed you can go back to your document right click on your index.html file and click open with live server and then in your chrome browser you should see tile map and there is a canvas you just can't see it yet let's go ahead and add some styling so our application doesn't look so bland inside of the head tag we're going to go ahead and add a style tag apply some styling to the h1 we'll set the color to light gray and we'll also align the text center on the screen then we're also going to set styling into our canvas which is called the game so we'll use the id selector and what we're going to do is we're just going to add some box shadow so i'm just going to add 10 pixels 15 pixels blur and we're going to use the color black so when i hit save now you can see it looks like it's kind of floating off the screen and then there's our body i kind of want everything to be centered right now it's always sticking to the left hand side the canvas so easy way to do that is we're going to use display and set it to flex then we're going to use justify content and say the content is centered on the screen we're going to say the height and this is going to be mainly for the color that i'm going to be setting we're going to say it's using 100 viewport height and the background what we're going to do is we're going to set something called a linear gradient and inside that linear gradient we're going to give it a few properties these properties will determine how the colors are drawn on the screen so we're setting a color here and we're using numbers instead of hex and then we're giving it also a percentage saying where this color starts and stops and i mistyped that over there so it's rgb and then we're going to set a second rgb below here which i just duplicated that line to 17 51 and 161 and we're going to set that percentage to be 60 i click save and then we get this nice gradient color for the background of our application with our html and css out of the way let's go implement our game js even though we're not making a full game and just a tile map we might as well set up the basic building blocks of a game let's do that by opening up the game js file inside the game.js file we're going to import our tile map and then get our game loop going we'll do that at the top of our aim js over here so we just import a tile map from the tile map file you'll notice i do dot slash and that means the current directory so then we have our tile map imported but if we look at our and we go to the development tools in chrome we'll see that we're getting an error because we haven't exported a default from the tilemap js so that's easy to fix we just do export default class file map and now that error will go away back inside our game gs we're going to go ahead and grab a few variables that we're going to be needing we're going to grab the canvas and we're going to get that from the document.getelementbyid and we're going to get the element called game so if we go inside our index.html you can see that it's called the game the canvas then from that we're going to get the ctx which is the context what we're going to use to draw to the screen so we call get context we give it a 2d context is what we want another variable that we're going to want is the tile size so earlier we discussed that each tile is going to be 32 pixels and then we're going to initialize our tile map since we imported it and inside that i'm going to pass in the tile size let's go back inside our tile map over here and implement that constructor and inside the constructor we're going to pass the file size and then we're just going to set a variable for it and back inside our game we're going to declare a function called game loop now you can call this method whatever you want but i'm going to call it game loop to represent our actual game loop and then let's go ahead and take our tile map and just call draw on it this will be just a little bit of code that we're going to be executing on every single loop of the game loop even though we're not really changing the screen much but this is how you would traditionally write your game and then we'll have our set interval over here which will take in the game loop and update the screen using that method and we're going to update it to match our refresh rate so monitor refresh rate is 60 hertz so that means we have to update it 60 times every one second and now we're just gonna get an error saying that draw is not implemented we can just go inside of our tile map and create a function called draw that takes in the canvas and the ctx click save and now our error goes away so now we have our basic building blocks for our game here and we can start to build that tile map let's go to our tile map js where we're going to implement that tile map i've opened up the completed solution over here and as you can see our map is made up of these grids to represent these grids we're going to use an array we're going to use a two dimensional array actually what is a two dimensional array a two-dimensional array is the following it's an array with other arrays inside it so it's going to look something like this so this is what two dimensions are there's the outer dimension and then we can figure out the number of rows by the number of other arrays inside here then we can figure out the number of columns by the number of items that are inside each row so let's go ahead and implement that let's start by making a little legend a little legend we're gonna do we're just gonna do above the map here and we'll just do as a comment the one will be equal to walls zero will be equal to our dots two will be our pacman and three will be the enemies now what does that mean well this will be number one one one the dots will be zero i chose zero just because it looks like a dot and then let's go ahead and implement that first row right there so to implement that first row we're just going to go to that first array inside there i'm just going to put a bunch of ones so i have about 15 ones over here that i've added and that would represent my first row then i could build my next row so the next row has a wall and then it's a whole bunch of dots in the middle so what i'm going to do is i'm actually going to copy the first row paste it in down here i'm going to go ahead and replace all of these with zeros the way i'm gonna do that is i'm gonna use this nice little feature inside of visual studio code where i can have multiple cursors and the way that you do that is you select the first item over here one and then you hit command d on mac or control d on windows and every time you click it it will add another cursor then i can change all those values in one shot to zero as you can see we have a one here then zero zero zero zero and then one and then click save and then we'll add pac-man as well over here so pac-man will be number two and in this particular example we have an enemy at the end so there would be a three over there so let's just go ahead and we'll implement the rest of these rows as well i'm going to copy that one that we had there again but what i'm going to do this time is i'm just going to set that two and three to zero then i'll go ahead and just duplicate those lines and then i'm gonna copy that top line over here and i'll go ahead and close that off so we have a wall at the bottom so now basically we have this big enclosure with walls all around a single pac-man and a single enemy over here next thing we're going to want to do is get this pac-man level displayed on the screen so the way we're going to do that is we want to use these images that we have in this example of a tile map that we're building we're using individual images another way of doing this is with a sprite sheet so in this example let's go ahead and just use these individual images in order to do this we're going to load our images and i'll show you how we can do that loading images can be a little bit cumbersome so we're going to go ahead and add a helper method we're going to call that hash image hash means that it's a private method and we're going to give it a file name it's going to take in and it's going to create an image object and that image object we're going to set a path on it so we're going to use backtick over here which is the symbol beside the one on your keyboard and we're just going to create a string and that string is going to be the path to the images so give me images so we go inside the images directory and then we give it the file name so that's the object we're going to pass in there or the string then we'll just go ahead and return that image now we can use this helper method to go ahead and load our images in the constructor so go ahead and define a wall and call that helper method and all we have to do is give it name of the image with the extension then do the same thing for the rest of the images so we'll grab our pacman we'll grab the dot the ghost and if you make a mistake with your images what's going to happen is you're going to get a 404 error make sure to keep your console open i called this one pac-man and this one's called pack one because that's from the game development tutorial on pac-man that i had so what i'm going to do instead is i'm going to just rename that image because pac-man seems like a better name for it and then i'll save it and then error message will go away before we draw our map let's set the canvas size the canvas right now is kind of tiny and won't really fit our map the information that we know about our canvas is we know that each tile is 32 pixels so inside of our draw method over here we're going to create a new method a private method called set canvas size and that's just going to take in the canvas that we're passing into our draw over here and then we're going to go ahead and implement that method so set canvas size takes in the canvas and then inside here all we need to do is set the canvas height and the height is going to be equal to the number of items in our array so we'll say map dot length times this dot tile size and then if i hit save i'm gonna see that our map grew and then we do exactly the same thing for the width except for the width we want to know the number of columns that we have so that's really simple all we have to do is take the first row inside that array and then do dot length so that's just getting this array over here and then getting the length of that array and do the same thing now watch as i hit save you're going to see that this grew wider next we're going to go ahead and clear the canvas so we'll do that inside the draw method and we're going to create a method called clear canvas it's going to take in the same properties that we have inside of draw so the ctx and the canvas then we'll go ahead and define that function below here and we'll pass in those same properties that we have right here the canvas and the ctx and all we need to do is say ctx dot fill style is equal to black and then ctx dot fill rectangle need to give it an x and a y coordinate so it's going to start at the corner over here and then we're going to make something that's the same width and the same height as the canvas and then click save and we have cleared the screen now we can go ahead and add another method called draw map we'll add the draw map function and all it's going to take in is the ctx now let's go ahead and draw that map the way we're going to draw the map is we're going to go row by row drawing every single cell as we loop over it one of the simplest ways to achieve this is just to use a for loop so we'll start by looping over the rows we'll just set up this for loop over here where we loop over the map so we figure out from the map what the length of it is which will tell us the number of rows and then we just increment that row once we get to a row we start to loop over the column that's why i set up a column variable here and then we loop over the column being less than this dot map and it takes in the row so the variable from the previous line then all we do is get the length of that which will give us the number of columns in that row and then column plus plus to loop over each individual one then what we do inside here is we can just create a constant called the tile and that will give us the value of that tile so we say this dot map and we give it the two variables that we have for the row and the column and that will give us the value for that particular cell and that value represents the image that we're going to be using so next we'll go ahead and we'll define a variable called image and we're going to set that to null and that value is going to be controlled by a switch statement a switch statement which will take in the tile value so in our first case we'll say case number one if it is case number one and it's equal to one that value then we'll say this the image is equal to this dot wall and if that's true we'll break then let's go down over here before we implement all of them so we can do this piece by piece we'll go ahead and we'll add a method called draw image on our ctx which is going to draw that image to the screen and that image we're going to have to give it an x and y position to figure out where we draw the image in terms of this column and rows that we have within the grid we have to find its location so to start off with we have that column value so we can take the column value over here and say this dot times the tile size which will figure out where we are in terms of the x position then to figure out the y position we're going to say that we're going to take the row times this dot tile size and then lastly when we draw that image so that'll find the position then when we draw that image we also need to give the size of the image we'll give it the tile size and this dot file size when we hit save over here it's going to draw some of the bricks we're encountering an error because the image is null in some instances right now so we'll do is we'll just add a little guard over here and we'll say if the image does not equal null then we get our bricks drawn let's implement drawing the rest of our images following our legend so going with the dots we're going to add another case over here and we're gonna do case zero you can see it's not formatted nicely but as soon as i hit save it'll format it and we'll say our image is equal to this dot dot and then we'll do a break and i'm gonna hit save and now we get our dots these blank spaces over here this is where pac-man is and this is where the enemy is so right now remember it's just skipping over anything that we don't have an image for now for case two what we're going to do is go ahead and drop pac-man according to our legend we'll grab pac-man over here we'll say this.pac-man and then do a break and lastly for case number three we're gonna go ahead and draw the ghosts and do a break there hit save and now we have pac-man and our ghost now we can go ahead and design our level current project setup of having live server and being able to save the file and have the changes immediately shown will make it easy to design the map also visual studio's multiple cursors makes it easy so right now i'm just selecting this and then i'm clicking command d or control d on windows and it's just selecting all those common values one after another and adding a different cursor but then i can change those values to one and click save then to do vertical lines down what i could do on a mac is i can do command and alt and down like that then i can have multiple cursors there and change those to one if i want to and click save which is really cool i could drop one down over here and put one and then just go modify that last one down there because i don't want that to be one and then i'll add another line and then let's go ahead and just quickly add some over here so if you learn how to use the editor properly you can quickly make edits like this then in the middle over here we're going to do is between this wall there we're going to add like a little be a little block of um like a big chunk of wall that we're going to add we'll make all of those one we'll make that one that one click save and there you go we have a chunk of wall and then what we'll do over here is we'll do something similar as well and i'll put a little link in the description to how you can do this in visual studio code to quickly edit your file and there you go we'll click save and we'll just do another wall there because you always want pac-man to typically just run down corridors not to really go into big open areas to make this map a little bit challenging too you could even add more enemies so anytime it sees number three it will draw an enemy on the screen i want to make it super challenging there's pac-man put an enemy right beside him and depending what random direction that enemy decides to move you might eat pac-man right away but you probably wouldn't do that but we could probably add an enemy down here one last thing we can do is understand exactly how the map is being built we saw that for loop of rows and columns now let's see it in action as the map gets built so inside chrome i've set up a breakpoint and that breakpoint gets hit just as we draw an item every time i click next it's going to draw a piece of the map as you can see it's drawing the first row which is all bricks then we get to the next row where pac-man is and a bunch of the dots and the enemy and we can see that it draws one after another so it's kind of cool everything gets drawn from the top of the screen from the top left down to the bottom right and one row at a time because of this for loop that we have over here i just wanted to show you that just to give a really good understanding of how the screen is being drawn there you have it we've designed a map for the pac-man game and that's how you build a tile map for a 2d game if you're interested in making the full version of hackman check out my pacman tutorial in that tutorial we build a fully functional pac-man game complete with sounds animations enemy ai collision detection and tackle core gaming concepts if you enjoyed this tutorial and want to see more subscribe like and share
Info
Channel: Coding With Adam
Views: 1,566
Rating: undefined out of 5
Keywords: javascript, tutorial, javascript tilemap, javascript tile map, js tilemap, 2d tilemap, how to make tilemap, vs code tilemap, pacman tilemap, pacman tile map, explain tilemap, game development, tile maps, tilemaps, tilemap
Id: KsLChm2MIQY
Channel Id: undefined
Length: 23min 26sec (1406 seconds)
Published: Tue Aug 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.