JavaScript 2D Game Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Hey Frank, just so you know: you are awesome. I watch your videos and I learned a lot from the knowledge you share. I think you are a good teacher

👍︎︎ 6 👤︎︎ u/irosion 📅︎︎ Nov 20 2020 🗫︎ replies
Captions
that was close the main reason that people don't succeed in becoming a self-taught front-end web developer is because they lose motivation it's very important to keep yourself engaged and have some fun while learning let's practice fundamental vanilla javascript principles and techniques today and build the game completely from scratch javascript runs in every browser on every computer and on most phones these days learning how to use it will give you so many job opportunities especially from 2021 forward we are seeing a huge shift towards online business everywhere it can also allow you to unlock your creativity and express yourself in many ways which can be a lot of fun my mission with this channel is to explore what can be done with javascript look both into its creativity and practicality and merge them together to make something new fundamental understanding of the language that only comes with repetition and practice is the best investment you can make in yourself and in your future i know some people tell you it's too late to start a career in web development but i say if you want to work with html css and javascript there have never been more opportunities than there are right now this is a great time to skill up and change your life the question is not is it possible to get a job the question is do you want it hard enough to invest in yourself and do what it takes you are searching for coding videos on the internet so i'd say you are already ahead of so many people who don't take action well done to be successful you need to be prolific at least for a while you need to learn create and repeat over and over until it becomes easy it will happen faster than you think but it can still take a while so who says we can't have fun while learning let's build a game [Music] i built a couple of game prototypes for this tutorial so far we have three different levels you can see level one is shallow sunny sea level two is a dark ocean depths i will show you what i did for level three later the game loop can be for example that we score points for popping bubbles and avoiding enemies and once we reach a certain score we advance to the next level in the first level we have to pop as many bubbles as possible while avoiding hungry sharks i could have also made the birds drop something into the water that we have to avoid for example the shark switches between two animations regular swimming and when it's within certain distance from a player it starts snapping its jaws to indicate danger also little starfish in the bottom left corner winks every time we pop a bubble it is scared of sudden sounds the second level is a bit more difficult instead of having a single shark on the screen that follows a predictable path we have multiple dangerous jellyfish swimming sideways we need to be careful not to get stung by them sometimes there's also a submarine or large sea monster swimming in the background you better stay quiet and not provoke them who knows what else is hiding in the dark i also use two repeating backgrounds here one floats to the left and the other floats to the right i like to create natural animated scenes like this it could also make a cool animated background maybe interactive fish tank where you have to feed the fish or something when it comes to art sprite sheets and images in this episode i want to highlight this artist and his website there are plenty of freebies here we can use for our project today but if you want to create something more special the prices for his assets are very reasonable sometimes i just like to scroll through the arts to see what's available to get inspiration for my next game project more on that later in the video when we get to actual sprite sheets i'm not sure what to call this game bubble popper maybe if you have any good name ideas let me know in the comments below today we will build this game line by line completely from scratch using just plain vanilla javascript no frameworks and no libraries as usual for the first time in the series 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 the fish sprite correctly so it always faces 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 good quality base game skeleton that can be used for other projects not just for this particular fish game then we will start adding graphics particle effects polish it up and make it look nice and clean you can see i also included interactive bubble text from my previous video i'm not going to show you how to build that in this tutorial but if you want to go back to that video if you do it you can easily slot that code into your game some people skip my generative art and 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 i made a video on how to rotate elements on canvas recently today we'll use the same technique to rotate player character around and we will take it to the next level by making it face the mouse position and move towards it you don't have to watch any of my previous videos if you don't want to this tutorial is completely standalone i will explain all the code today but if you are struggling to follow at some point you can try some of the videos from my canvas playlist for beginners link in the video description you can try this first and then come back here later once you know the basics of html canvas and you have built couple of simple projects with it this video is not for complete javascript beginners but i will do my best to help you understand and make sure you are able to follow along click like please if you get any value from my tutorials you can also subscribe hit the bell icon and click all notifications to make sure you don't miss any of my future creative coding tutorials i'm trying really hard to keep you interested in javascript and have some fun while learning important vanilla javascript techniques if you can complete this tutorial and get to the end with me you have what it takes to get a javascript job let's dive deep into the coding part and take one more step towards front and web development mastery hope you have fun [Music] in index.html i create html canvas element with an id of canvas 1. i link style css file and my javascript file in style css i just do a simple reset to make sure my page appears the same in all browsers asterisk selector will target all elements margin 0 padding 0 and box sizing set to border box which means elements border and padding will be included in its total width and height i will show you a different way to center html element both horizontally and vertically using flexbox first i take the parent in our case body element and i make sure it covers the entire browser window by setting its width to 100 viewport width and height to 100 viewport height i also give it display flex which will affect how its children behave body element in our project has only one child and that is our canvas i grab it by id canvas one i want our game to have set width and height this time so with 800 pixels and height 500 pixels border 4 pixels solid black i need the spell height correctly zoom out a bit so we can see the whole thing now because body has a display property set to flex i can give it additional properties look what happens when i say justify content center it centers child canvas element horizontally and because body covers the entire height of browser window i can also say align item center which will align it vertically we will do everything else with vanilla javascript in script.js file to get our game to work we need to do 5 things we need to take care of basic canvas setup as usual we need to capture mouse position somehow and make it available all over our application we need to create player character we need to handle bubbles for player to pop and score points and we need to put all of that together inside animation loop canvas setup as usual custom variable called canvas will keep reference to the actual html5 canvas element so document getelementbyid one to gain access to built-in 2d drawing methods i create ctx variable shortcut for context and i set it equal to canvas variable from line 2 dot get context and i pass it 2d canvas width is 800 canvas height is 500 this needs to be the same values we set in css file i will create a let variable called score and i set it to 0 at first game frame variable will be initially set to 0 as well i will increase it by 1 for every animation loop so we can do things like spawn a new bubble every 100 frames and so on we can attach any game events to it so it comes quite handy i set canvas font to be 50 pixels of georgia for example we will use text to display score today to capture mouse coordinates and make them available all around the application i create a custom javascript object i call for example mouse i give it x-coordinate property and i set it to canvas width divided by two so middle of the screen horizontally its y-coordinate will be canvas height divided by two so middle of the screen vertically click will be false at start i will use this to see if mouse button has been pressed or released this custom mouse object just holds data i will now create mouse down and mouse up event listeners that will override properties on this object with current mouse information canvas dot add event listener takes two arguments type of event to listen for which is mousedown and callback function to run when that event occurs callback function has access to event object so i pass it here as an argument whenever we click a mouse mousex property on line 13 will be overridden with current mouse x coordinate and mouse y from line 14 will be overridden with the current y coordinate at which the mouse down event is occurring so on line 17 i'm passing something called event to a callback function on event listener this is a special built-in event object that holds a lot of information about the event we are listening for if i console log it we can see it holds a lot of information about that event that has just occurred the values we want is this x and y which i am referring to on lines 18 and 19 as event.x and event.y i can check if you are getting right values by console again mousex and mouse y now every time i click the mouse i get x and y coordinate of that click the only problem is that when i'm in the top left corner of canvas i should be getting coordinates 0 0 but i'm actually getting something around 40 for x and 200 for y that is because it measures distance from edges of browser window not edges of canvas element there are many ways to solve this what i can do today is create a custom variable called canvas position and i set it equal to canvas from line 2 dot get bound incline rectangle this built-in javascript method will measure current size and position of canvas element if i console log canvas position i can see it contains distance from bottom left right and top as well as height and width and x and y coordinates i can easily offset mouse position based on these values on line 22 mousex will be event dot x minus canvas position left mouse y will be event dot y minus canvas position top i can delete the console log on line 13 and if i console mouse x and mouse y on line 21 i can see it correctly goes very close to 0 when i'm near top left corner i don't need to try to click exactly pixel 0 0 to see that it works to create a player character i will declare javascript es6 class and i call it player with capital p constructor will contain a blueprint for all properties on player object so this dot x will be canvas width divided by 2 and this dot y will be canvas height divided by 2. these are just the initial starting coordinates before the player starts moving it will immediately start moving towards the current mouse x and mouse y position from lines 14 and 15. if these values are different player will move from coordinates on lines 26 and 27 to coordinates on lines 14 and 15 on the first page load i will show you what i mean in a minute when we get the animation working this radius will be 50 because at first player character will be represented by a simple circle this would angle will be zero at first i will use it to rotate player towards current mouse position when we give it a fish sprite sheet i want my player the fish to always face the direction it is swimming in this dot frame x and this dot frame y will be coordinates of currently displayed frame in fish sprite sheet since we are using multi-line sprite sheet we will also need this.frame property which will keep track of overall number of frames on the sheet and the current position we are animating we will get back to this in a minute this dot sprite width will be width of a single frame from my original sprite sheet this sprite sheet i'm using is 1992 pixels wide and it has four columns so 1992 divided by four is 490 its height is 981 pixels and we have 3 rows so height of single frame is 981 divided by 3 which is 327 pixels i will create a custom update method this method's job will be to update player position to move the player towards the mouse to do that we will need to compare player's current position and current mouse position we will create a variable called dx distance on the horizontal x-axis and it will be this dot x player's x position minus mouse dot x constant d y distance on vertical y axis will be this dot y minus mouse dot y now i will say if current mouse x position is not equal to current player's position this dot x minus minus i will do another if statement don't do else if here we want both of these to run at the same time i say if mouse.y is not equal to this dot y this dot y minus minus this will not work i can't just say this.x minus minus and this dot y minus minus player would be always moving to the left and upwards in minus directions on x and y axis instead i say this dot x minus equals dx from line 37 and this dot y minus equals d y from line 38 this way player can move both left and right because dx and dy can be both positive or negative numbers depending on relative position between mouse and player as we calculate them on lines 37 and 38. if i leave it like this player will move so fast it will look like there is no animation it will just jump to mouse coordinates when we click i want player to move to mouse position but with reasonable speed so i say dx divided by 30 and dy divided by 30. as i said in the beginning this is not tutorial for complete javascript beginners if you are struggling to understand what's happening here maybe you can watch some of my videos from the beginner playlist first and then come back here once you've built some basic canvas projects i'm happy to explain everything slowly but i can't explain every small detail in every video i do explain everything in videos that are aimed for beginners and have for beginners in the title i am still learning what is the best way to do these tutorials for you so give me your feedback in the comments please if you think i should have handled this better we will also need a draw method on line 16 i set click property on custom mouse object to false line 19 whenever mouse down event occurs i set mouse click to true on line 23 i create another event listener for mouse up event whenever mouse up event fires i will set mouse click to false now i can go back to line 51 and inside custom draw method on player class i can say if mouse click is true and here i want to draw a line from mouse position to the player so we can see the direction of movement let's just do a very thin line line width is 0.2 pixels i call begin path ctx move 2 will set start point for the line it will be the current player position so this dot x and this.y ctx line 2 will be the endpoint of the line so mouse.x and mouse.y when i call ctx stroke it will connect these two points we will see that in a minute i also want to draw a circle that represents player character i set ctx fill style to right begin path ctx arc to draw a circle and i pass it this dot x and this dot y for coordinates this dot radius for size start angle 0 and angle will be method by times 2 so full circle 360 degrees now i call ctx fill to draw the circle and i close path our custom player class is complete and i can now create a constant variable called player and set it equal to new player the new keyword is a special command in javascript it will go up to line 21 and class constructor will create one new blank player object and assign it properties based on class blueprint declared between lines 30 and 38. we created our player and gave it behavior with custom methods nice before we do the bubbles let's skip to animation loop so we have some visual feedback on canvas and we can see if our code is working correctly i create a custom function called animate inside i take player variable from line 65 and i call update method from line 40 to calculate player position i also call draw method to draw a line between player and mouse and draw circle representing the player i will call animate like this to run the code nothing is happening yet to create a loop on line 73 inside animate i call request animation frame built in javascript method and i pass it animate the name of its parent function from line 70. this will create animation loop through a principle called recursion where function calls itself over and over it still doesn't work i quickly check my code and i can see on line 14 i used capital x javascript is case sensitive and capital x is a different variable name than lowercase x if i fix it we get some animation player represented by red circle is leaving trail to fix that i go to line 73 and inside animate i call ctx clear rectangle and i pass it canvas dimensions to clear the entire canvas from old paint between every animation frame we have some movement on the first page load because update method on player class is always comparing player coordinates and mouse coordinates and correcting the difference on the first page load player starts at coordinates declared on lines 30 and 31 inside its class constructor and it moves towards a current mouse coordinates before we click mouse for the first time this initial mouse coordinates are declared on lines 14 and 15 so by changing any of these values i can change this initial player move when we first open the game if i want to test player behavior whenever i click the mouse it draws a line between mouse and player position for as long as i hold mouse button down the line is visible player also correctly moves toward the current mouse position this is starting to look good [Music] changing values here will change player movement speed now it moves so fast it seems instant if i divide it by 100 it will be quite slow dividing it by 20 makes it reasonably fast it only starts moving towards the mouse when we click time to create bubbles so we can pop them and score points this will be a very basic particle system at first i create a variable called bubble's array which will be set to an empty array at first class bubble will contain a blueprint so constructor will have this dot x for example random number between 0 and canvas width this dot y will be a random number between 0 and canva's height this.radius will be 50. i want all bubbles to have the same size this.speed will be a random number between 1 and 6. this distance will keep track of distance between each individual bubble and player so we can trigger score and pop the bubble when the player is near enough we will use collision detection between two circles here i create a custom update method which will just move bubbles up in negative direction on vertical y axis depending on their individual speed value so every bubble will rise at a slightly different speed custom draw method we'll just draw a blue circle for now i set fill style to blue begin path as usual ctx arc to draw a circle it needs x position y position radius start angle 0 and end angle math.pi times 2. i fill the circle and i close path we will use sprite sheet for the bubbles eventually but not yet on line 8 i declare the game frame variable this variable starts at 0 and down here on line 96 i will increase it by 1 for every frame of animation if i console log game frame you can see it increases endlessly as our game runs now i can use it to add periodic events to our game on line 90 i create a custom function called handle bubbles inside i say if game frame modulus 50 equals to 0 this means if game frame value is divisible by 50 with 0 remainder so this statement will be true at frames 50 100 150 200 and so on basically i'm saying run this code every 50 frames every 50 frames i will take bubbles array from line 69 and i will call built in array push method on it which method just takes whatever we pass to it and pushes that to the end of the array so i pass it new bubble this will trigger bubble class constructor and create one new bubble object and inserts that into bubbles array if i console log bubble array length and if i call handle bubbles on line 100 inside animation loop you can see that one new bubble is added to the array every 50 frames on line 95 inside the handle bubbles function i run through the entire bubbles array and for each bubble object in that array i call their associated update and draw methods it works we have bubbles now click the like please if you get any value from my tutorial also good job if you followed all the way here you're doing great practice makes perfect as you can see new bubbles randomly appear somewhere within canvas area i actually want them to appear below the bottom edge of canvas and just float in so on line 73 inside bubble class constructor i set initial vertical y-coordinate to be canvas height plus mass at random times canvas height canvas is 500 pixels tall so it will be a random number between 500 and thousand that looks better in console i can see bubba's array is growing endlessly we actually don't want that on line 95 inside a for loop that cycles through the entire bubbles array i say if this bubble's vertical y position is less than 0 which means it has moved past the top edge of canvas called splice method splice method will cut out element at certain index from the array it needs at least two arguments the first one is index of the object we want to remove so i pass it i which represents the bubble that has vertical y value less than zero and i also pass it one to specify that i only want to remove one element from the array after this index in console i can see that it's working particles array length stays around seven new bubbles are being added and old ones are being removed the problem is that every time i splice one bubble from the array all bubbles blinked for some reason the animation stutters it's because i'm updating and drawing and removing bubbles in the same for loop i don't really know why this blinking occurs if anyone knows please leave a comment i will try to figure it out later the way to fix this is to simply create another for loop that cycles through the same array and put the splicing action into this separate loop instead this is not a good practice to cycle through the same array twice like this but since the array only ever holds such a small amount of bubbles it's not really noticeable in performance this could cause issues in large scale particle systems so keep that in mind i can also see that bubbles are disappearing too early before they fully disappear behind the top edge of canvas i will fix it by adding 0 minus this.radius times 2 here on line 100. we have similar issue on the bottom edge new bubbles spawn at random position between 500 and thousand pixels from top edge of canvas as we declared here on line 73 if we get a random value close to 500 we can still see part of the bubble appearing instantly i need to add plus hundred to the minimum value to make sure new bubbles appear in are always completely hidden below the bottom edge maybe i could even completely remove the random position here and make new bubbles always appear at the same vertical position it should still look good yeah it's fine i go down to line 112 and inside animate i call ctx fill text it expects three arguments text to display and x and y coordinates where on canvas i want to display that text so as the first argument i will concatenate static string that says score colon space plus dynamics score variable from line 7. i also pass it 10 as horizontal x position and 50 as vertical y position the text is right let's set fill style to block on line 103 inside handle bubbles i want to check the distance between player and bubbles if they are close enough and collide i want to add plus one to score and remove the bubble from bubble's array let's just write this line of code first and explain it once we see it i say if distance property on this bubble particle is less than this bubble's radius plus player radius i know collision is happening so i will console lock collision we are doing simple collision detection between two circles the way this works is i calculate distance between two points on canvas the first point is the center point of circle that represents bubble and the second point is center point of circle that represents the player we know that two circles collide if the distance between their two center points is less than radii of these two circles combined so here i am checking for distance property on bubble object i declared it here on line 76 but i haven't written code to calculate the distance yet same as we did for checking difference between mouse and player object earlier i will create dx and dy variable dx distance on the horizontal x-axis will be the difference between this dot x which is in this case this bubble minus player's current horizontal x position player x d y distance y will be distance between y position of bubble minus y position of the player once we have these two values we basically plot an imaginary right angle triangle where one side is a dx one side is a dui and the distance between the two points is the hypotenuse the longest side of right angle triangle we have two sides of triangle and we know there is right angle between them so we can use pythagorean theorem to calculate the longest side which will be the actual distance between two center points we also calculated dx and dy here on line 41 and 42 to calculate distance between player and mouse we are doing the same thing here again but this time it's between player and each individual bubble and we are taking it to the next level by actually calculating distance from these values the formula is this the distance equals math square root dx times dx plus dy times d y we are consoling collision detection and i can see that whenever red player circle overlaps with any of the blue bubbles we get collision warning in console great that works so here on line 108 whenever collision is detected i want to increase score by one that works but i can see that each bubble keeps adding points to the score as long as it's overlapping with player we would get a lot of points easily like this i want each bubble to only ever give one point to do that i go up on line 77 and on bubble class constructor i add one more property called this dot count it and i set it to false at first down here on line 109 inside distant check if statement i say only if this not counted is false exclamation mark means false and then take the same bubble object and set its counted property to true doing this will make every bubble to only get counted once once we collide with that bubble i also want to remove it from bubbles array by calling splice on the array i pass it i variable which is index from the for loop to specify which bubble i want to remove and i also pass it one we want to remove one element at this index i delete console log on line 108 and i also delete console log on line 97. so how do we make the game play popping sound whenever we collide with the bubble and score a point first of all let's use two sounds to make it less repetitive on line 78 inside bubble class constructor i create another property called this dot sound i want this property to have a random value which will be a string that says either sound one or sound two it will be randomly assigned whenever new bubble is created one way we can randomly assign one of two available properties is by using so-called ternary operator which takes three operands basically it's a one-line if-else statement that's all math at random called on its own like this returns a random number between 0 and 1. so i say if this random number is less than or equal to 0.5 which should roughly be in 50 of the cases then question mark assign value sound 1 to this dot sound property else colon assign it sound 2. if we look at this line again i'm saying if this condition is true then question mark return sound 1 else colon return sound to very simple one line if else statement if you get used to this syntax it's called ternary operator and it's one of the new javascript es6 features now i need to bring the actual sound files to the project down here on line 96 i create a variable i call bubblepop1 and i set it equal to document.createelement and i pass it audio as an argument then i take this bubblepop1 variable and i set its src source property to the path to my sound file to get sound effects for my game i can go for example to opengameart.org and if i search for bubble and select sound effect here i can see we have summer matches i can play the sound i think i will take this one this is ogg file that should work and maybe this one there are multiple files here i will download these three and see which one i want once you place the sound files into your project folder you can reference them with javascript here i also create bubblepop2 everything will be the same just the source will be pointing towards a different sound file i choose one ogg file and one waff file both should work let's test it on line 115 i say if this bubble's sound property is set to sound one then i take the first sound saved in bubble pop 1 variable online 96 and i call play on it like this else i play bubble pop 2. on line 97 i need to make sure i use the correct file name oh actually same online 99 that works whenever we pop a bubble now we randomly get one of the two sounds we choose let's bring in sprite sheets since some of you don't have photoshop and i want everyone to be able to follow this tutorial we will have to work with three available tools to make the sprite sheet move without restructuring it i can't just adjust the sprite sheets myself in photoshop and give them to you for download because i don't own these images and i can't redistribute them like that they are free but you have to download them from the site yourself you can also use your own sprites as usual if you want i really like this site gamedeveloperstudio.com you will have to register to access even the free spreadsheets but it's just a simple name and email they don't ask for anything else i recommend you look through some of these sprites it gave me so many ideas for games i can build in the future i really like this cartoon art style you can find some free or very cheap beautiful sprites for your games here if i sort out the assets up here by price from the cheapest we have all different game images and sprites here here on page two we have two different fish that are completely free and also some bubbles water effects and fish food we can use for the game later i've already downloaded this fish that's why it says re-download here if you get the zip file and unpack it inside there is a folder called sprite sheets and there we have pre-rigged sprite sheets for six differently colored fish all are facing left and each has idle and swim animation let's grab the swim animation i will use the redfish but you can use any color you want i rename it to fish underscore swim underscoreleft.png i place it directly in my project folder and i set player left src to this image i also create player right set it equal to new image and i set its src to fish swim right png i want to rotate the fish around in a circle to always face the mouse and the direction the player is moving to do that i have to do something a bit weird now since some of you don't have photoshop i will use free online tools so that everyone can follow i go to google and i search for something like flip png vertically it's this first link i can take the fish swim left file and i drop it here it will just flip it upside down like this i save that file and i rename it as fish swim right png flipping the whole sprite like this is not the cleanest solution ideally we should break the sprite into individual frames first and flip each frame one by one and rebuild the sprite sheet in the same order because i flipped it like this the rows of images are organized in the opposite direction so for some sprite sheets this will break their continuity it's easy to do if you have any graphics software there is also a free online tool that allows us to slice spreadsheet into frames and then we can rebuild it again if you want me to show you let me know for now let's just get this to work and see what it looks like so i have both player left and play right images set up ideally this would be on a single sprite sheet but i don't want to make these tutorials expecting that everyone has access to photoshop or some other advanced graphics editors so what we did here is basically a workaround down on line 70 inside the draw method on player class i call built-in draw image method it has three versions we can pass it three five or nine arguments depending on how much control we want to have over the image since we want to animate a sprite sheet here we will use the longest version that takes nine arguments the first argument is image we want to draw the next four arguments indicate area we want to crop out from the source sprite sheet we want to crop out only one frame at a time the last four arguments define where on destination canvas i want to place my cropped out image onto so as the first argument i passed the image i saved it as player left variable the next four will be x y width and height of the source image to indicate area we want to crop out to get just one frame i have explained it in detail in previous beginner friendly episodes so today just quickly source x is this dot frame x times this dot sprite width source y is this dot frame y times this dot sprite height source width and source height will be this dot sprite width and distal sprite height we cropped out a rectangle from the source sprite sheet the last four arguments determine where on canvas we place that cropped rectangle so i just place it wherever the player currently is this dot x this dot y and i want to scale it down because the image is too large so width and height of image drawn on canvas will be this two sprite width divided by four and this dot sprite height divided by 4. we have our fish the red circle is the original player area and it is also area where collisions between red player and blue bubbles are detected so i want the image of the face to cover the red circle as closely as possible to do that i have to play with this dot x and this dot y and adjust it somehow these values will be different for every sprite sheet the fish is always facing left i want it to face right when it swims to the right so on line 69 i create an if statement that says if this dot x is more or equal to mouse x i take draw image code we just wrote and i pasted it here then i create an else statement and i copy the same draw image code in there as well in the first one i change player left to play right to use the other image we flipped vertically okay i did it the other way around the first one is player left the other image inside else statement is player right that's better now i want to rotate the fish around to always face the mouth and the direction it is moving canvas rotation is a bit complex for beginners i have a special episode in my beginner playlist that explains this in detail first i call safe to save current canvas settings then i call translate and i pass it players current x and y to move rotation center point where the player currently is then on line 73 and 75 i replace this.x and this.y with 0 because player position is now reflected in translate call on line 721 then i call ctx rotate and i pass it this dot angle from line 38 after draw image i call canvas restore which will reset all translate and rotate cores back to how they were when we last called ctx safe in this case online 70. this way only the player gets translated and rotated and it will not affect bubbles score or any other elements we will be drawing later now if i change angle the rotation of player changes like this how do i make angle rotate based on relative position between player and mouse on lines 46 and 47 inside update method on player class we are already calculating horizontal and vertical distance between two points between player and mouse we can use these values and calculate so-called theta which is the counterclockwise angle between x-axis and any point i will make a special video on this in the future to explain it in detail for now i will just show you how it works let theta is equal to math.a-tan math.atan2 and i pass it d y comma dx as arguments then i just assign this angle value from line 38 to theta value we just calculated on line 48. since update method runs over and over this angle will be recalculated for every frame of our game and fish will always correctly face the mouse now sometimes if i pop the bubble very close to the top edge splice method has already removed that bubble from the array because it disappeared past the top edge but it's still registered as collision so javascript will try to run splice on the same bubble again but it doesn't exist because i have two different splice calls in one for loop to fix this down here on line 127 i cycle through bubbles array on line 128 i check if bubble has disappeared over the top edge and if so i remove it with splice then we have another if statement that checks distance between player and bubble and if the first one runs i don't want the second one to run because that bubble has been spliced already and removed i could just do if else here or i can just say only run this code if this bubble with index i still exists okay challenge time there is a bug in our game currently when i resized the browser window it doesn't register mouse position correctly anymore you know how to fix that can you find any other bugs let me know in the comments down below we will build the rest of the game in the next episode click like if you want more videos like this one and you learned something new today you can also subscribe and hit all notifications to know when the next video comes out while you're here i have other creative coding tutorials and game development playlists all with manual javascript with no frameworks and no libraries you can check it out if you want see you next time
Info
Channel: Franks laboratory
Views: 68,851
Rating: undefined out of 5
Keywords: javascript 2d game, javascript game, javascript tutorial, javascript game tutorial, javascript 2d game tutorial, html canvas, html5 canvas, game tutorial, canvas game tutorial, how to make a game, javascript, vanilla javascript, vanilla javascript tutorial, learn javascript, web development 2020, learn web development, web development tutorial, frankslaboratory, franks laboratory
Id: jl29qI62XPg
Channel Id: undefined
Length: 44min 42sec (2682 seconds)
Published: Fri Nov 20 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.