How to Code: Collision Detection — Part I

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
collision detection is simply determining when two objects touch if we're able to tell when two objects are touching we can react to the event in different ways we can have the object bounce off of each other we can remove an object from the canvas or we can even increase a user score given that we're programming a game to implement collision detection we need to know how to use a mathematical function called Pythagorean theorem the Pythagorean theorem is a formula that'll always get the exact distance between two points by taking the X distance between two points the Y distance between two points multiplying these distances by a power of two and then running the result through a square root function will always be returned the exact distance from point A to point B thanks to our friend Pythagoras and geometry so with this in mind let's see how we can calculate the business between two points and implement collision detection welcome back everyone this is going to be another Chris course with your host Chris and in this episode I'm going to be teaching you guys how to code collision detection with html5 canvas so the first thing I'm going to do is I'm going to open up my terminal window and I'm going to CD into a directory which I like to code most of my web projects in so I like to code most my web project in a directory called web so I'm going to go inside of there and once I'm inside of here I'm going to clone a repo called canvas boilerplate and this is a boilerplate that I use for pretty much every canvas project that I create and if you'd like a detailed detailed walkthrough on how to download and use this boilerplate and head on over to the how to code gravity course and I do a more in-depth tutorial in comparison to what I'm about to do right now so to keep things brief I'm going to clone this repo into a directory called collision detection and this is just going to copy all the contents within this repo into a directory called collision detection so once that is finished up I'm going to CD into this repo so CD collision detection that's going to put me right inside of that folder so once I'm inside of the folder I'm going to open it up in sublime text so my method of opening this up is by using this alias I have right here this is a custom alias so if you don't have this and just go ahead and open this up and find her and go ahead and drag collision detection on top of your sublime text icon and it will open it up for you in sublime text so once you have this opened up in sublime text we now need to download all the dependencies within our package.json file so to do that you can either run npm install install or you can run yarns and both are going to do the same thing it's just going to contact a server out there and npm server and it's going to download all of these dependencies listed out within this package JSON file and these are used for a number of purposes if we download all these dependencies while we can make use of things such as es6 which allows us to make use of next level generation of java scripts things such as let's constants and so forth and it also allows us to make use of browser sync will to manage automatic page refreshes whenever we make a change to one of our files so by downloading these packages were able to do a few extra things which which will enhance our development workflow so that's a whole reason of downloading this repo in the first place so let's go ahead and run web pack in the terminal we can only run a web pack in terminal once we actually download all these packages and once that happens it's going to open up a new tab in one of your browser windows and if I drag that on over here you'll now see I have a canvas project ready to go for development in the browser so to get started coding coalition detection we are going to head on over to the source file canvas j/s and if you're unfamiliar with the file ID Tayla now and the how to code gravity course line-by-line so if you're unfamiliar with this right now and you really want a more in-depth explanation now Helen over that course and just watch the intro and once you're done watching how to install the boilerplate and how to use is canvas guess I'll head back on over here and we can get started so first thing first let's clarify what we want to happen in regards to collision detection so there are multiple ways that do collision detection can detect when the mouse goes inside of a circle we can detect when two circles touch each other we can detect when two rectangles touch each other or we can detect when two polygons touch each other but we are going to be focusing on when two circles touch each other mainly because it is going to it's going to lead into part two of this series in which we create a animation a physic simulation in which we have multiple balls bouncing off of each other instead of just two so this is going to be the most basic collision detection we can come up with two balls colliding with each other and reacting once they collide just to the next one we'll get to more than two so if we are going to create two circles that collide with each other well I guess we need two circles on the screen so instead of a generic object we are going to rename this to circle with a capital C since all objects are going to be capitalized and you can see we already have some properties laid out for us in regards to the circle object we have things such as an x and y coordinate we have a radius and we also have a color for the circle as well so we now need to actually instantiate a circle we need to create a circle whose properties and method are independent from any other circle that we create so to do this we're going to head on down to our implementation sections and we're going to create a new variable but instead of var we're going to be using what and that is a feature of es6 that it's basically the same thing as bar but it is takes scope into account which bar does not if you'd like to learn more about this while there are plenty of good courses out there on es6 if I were to recommend one I would check out layer cast comm they have a great course on introduction to es6 go ahead and check that out but just know what is basically the same thing as far it's just an improved version so we are going to be declaring a let called circle one this is going to be equal to a new circle capital C just go ahead and give it an x-coordinate and 300 and a y-coordinate of 300 as well when it comes to their circles radios will just say we will just give it a large radius of 100 and we're going to make this circle black all right so we're creating a circle and we're storing it within the circle one variable but usually it's best practice to set these variables within this emit function basically you declare them outside of the knit function and set them with inside of it so what this would look like is we would grab what we're setting right here declare the variable at the top and then we'd set circle one equal to a new circle within this emit function and this emit function is being called once at the bottom before the animate function but it's also being called whenever we resize the browser and this is going to come in handy down the line once we want to reset all the objects on our screen due to a window resize rather than creating new ones each time the browser window gets smaller or larger you'll see you down the line just hang tight with me so just know we always declare a variable outside of in that function but we set it inside of it so we're not seeing anything as of yet that is because although we are storing an object inside of circle one we now need to actually draw that object on the canvas and all of our drawing is going to take place within this animate loop so we can go ahead and get rid of this filled text right here and we are going to say circle one dot update and this update function is going to call this right here which in return calls this draw function which is this right here what this is going to do it's going to take all the properties that we set over here and it's going to store them within each individual objects properties and the properties are used within this draw function so as a result each time we call the circle that update function we are creating a new circle in the middle of our screen since our animate loop is running over and over and over and over again so we have one circle on the screen but now we need to draw another circle and let's have a circle faller a mouse whenever wherever we move it on the screen so to create a circle that follows the mouse we are going to create another circle within our implementation so we'll say circle two and now we need to set this circle so we'll copy this line right here paste it beneath it then we'll say circle two is equal to an x-coordinate of undefined a y-coordinate of undefined and let's see let's go ahead and make this radius equal to 30 instead of 100 make it a little smaller and we'll go ahead and make the circle red so what's going to happen is we're going to be moving our red circle around the screen and once it collides with this black one in the middle we'll go ahead and change the black one to red once we move our red circle outside but it'll change back to black and that is how we're going to react to this collision detection so now we need to actually draw the circle on the screen but we want to make sure that the circle is following our mouse wherever we move it so we are going to be saying circle to not update and that's going to draw on the screen but in order to actually get this moving in regards to our Mouse's positioning we need to alter circle twos x-coordinate to be equal to the mouse's x position and mouse dot X this is just a variable that's declared all the way up here at the top and we are setting this variable each time we move our mouse across the screen using this event listener right here all this is doing is its grabbing our Mouse's x-coordinate and placing it within this variable called mouse x for readability purposes so we're setting circle to s x value equal to mouse x but now we need to set several 2's Y value equal to Mouse Y and if we save that and move our mouse across the screen we are not seeing anything at the moment and that just means that we have a bug so let's see circle 2y is not a variable we need to access property from not a variable and there we go okay so we have a circle being drawn on screen and if you see we move our mouse a circle is now following our mouse wherever we go but if we touch this black circle and the center you'll see nothing is happening we're not actually detecting any collision at the moment and that's what we're about to implement so to actually implement this we need to make use of something called the Pythagorean theorem and basically the Pythagorean theorem is just a formulaic math function a formula that is used to calculate the distance between this red circle and this black circle the Centers of both of them any two points on the screen the Pythagorean theorem will get the distance between - no matter if it's diagonal vertical or horizontal to the to the corresponding point so to make use of the Pythagorean theorem we're going to be creating a new utility function called get distance and this function is going to take four argument the first two arguments it's going to take is the x and y-coordinates of our first circle so that is going to be x1 and y1 and then the last two arguments are going to be the x and y-coordinates of our second circle so that's going to be x2 and y2 all right so that is going to be the first step to computing the distance between our two circles but now we need to actually implement some coding here that makes use of these varying varying coordinates between our two circles so to do that we first need to get the distance between our x-coordinates so to get the distance between our x-coordinates we are going to say let X distance be equal to x2 minus x1 and that is going to get the distance the horizontal distance between this X 2 coordinate and this X 1 coordinate but we also need to get the distance the Y distance between these two points as well so we'll say Y distance is equal to y2 minus y1 and that's going to get the Y distance between the two points as well so once we have the distance between these two points we can now insert them into the Pythagorean theorem so to do this we are going to be returning a value and the first thing we need to do is we need to raise this X distance to a power of 2 so to do that we're going to say math how this is going to calculate what happens if we raise a certain variable to a specific power so the variable we want to raise to a specific power is going to be X distance we're going to raise this to a power of 2 like so and that's really all we need to do so once that's in place we also need to do this for our Y distance so we'll say math.pow y distance raised to a power - and then to finish this formula off we are going to square root the entire thing so if square root the entire thing we're going to prepend all this with math sq RT which stands for square root and we're going to wrap the entire thing in parentheses and with that in place all we really need to do now is make use of this function to get the distance between the two points so we're going to copy get distance we're going to head on down to our animate function and let's go ahead and console.log the sound so we can get a better idea of the numbers going on behind the scenes so we'll say get distance and then we'll select our circle ones x-coordinate then we need a y-coordinate so circle one not why and then we need our second circles x-coordinate so circle 2x then we need the y-coordinate as well for circle two so we'll say circle two dot y so we'll save that and open up our console now whenever I move this red circle around you'll see that the numbers are changing over on the right hand side and the closer I get to center of the black circle the closer to zero we are going to be and eventually we are going to get some number around zero so you'll see that we're calculating the distance between the two centers of the individual circles the farther away I go the bigger the number gives no matter to stye agonal horizontal or excuse me vertical or horizontal so now all we need to do is we need to determine when the edge of this circle touches the edge of the black circle we need to determine what should happen as a result so to do this we need to add an if statement within our animate function and we are going to make use of what we're constantly getting out here so we'll say when the distance between the two points is less than the radius of both the first circle and the second circle then we are going to react to this event by changing the color of the black circle and we need to take the radii into account here because we're not changing the color of the black circle when the center of the red circle touches we want to change the value when the center of the red circle plus it's radius is touching the center of the black circle plus the black circles radius and that is going to allow us to react to a collision event so what we'll do is we'll say Circle one dot radius plus circle to that radius so if the distance between these two points is less than the combined value of the two circles radii then we are going to change circle one color to be red and let's go ahead and test this out so you'll see they're touching right now and let's let's see if we can test this out with that at touching from the beginning all right so right now they're touching and is turning red automatically because our circle is spawning in the middle of the screen so right now our circle is spawning an undefined location let's go ahead and spawn this a location of ten and ten so we can better exhibit what's really going on here okay so it's not actually it's not the circle is and actually being spawned based on these coordinates actually being spawned based on our animate function Center since our anim function is being read over and over and over again so you'll see from the beginning circle to X and circle to Y is equal to mouse to X and mouse dot Y so we'll go up to our mouse X and we'll set it will set its initial value equal to ten and we'll set its initial Y value equal to ten as well and that should fix things up a bit all right there we go so now our red circles being spawned in top left corner screen and once we get touching to this black circle watch what happens you'll see immediately it turned red but once we go off of it it's still red so we want to make sure that we change it back to its original value so really to do this it's quite simple we'll just add else statement to the end of this if statement and we'll say if the two circles are not colliding if they're not touching circle ones that color will be equal to blank and with this in place let's watch what happens let's go ahead and move closer BAM and then we would go off of it back to black so red black red black red black this is how you implement collision detection using two circles two basic objects within a canvas piece so that's going to be a further some folks I hope you now have a better idea of how to create collision detection between two objects using yes in the next video we are going to be covering collision detection between multiple objects so that when multiple balls are bouncing outside the screen they actually bounce off of each other instead of passing through one another individually so I hope you're excited everyone and I look forward to seeing you in the next episode [Music]
Info
Channel: Chris Courses
Views: 206,356
Rating: undefined out of 5
Keywords: collision detection, html5, javascript, tutorial, collision, canvas, game programming, programming, game development, development, web, lesson, education, canvas element, javascript collision detection, webpack
Id: XYzA_kPWyJ8
Channel Id: undefined
Length: 17min 25sec (1045 seconds)
Published: Tue Jun 06 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.