2D Physics -- Godot 3 Tutorial Series

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody it's Mike here game for scratchy today we're gonna be jumping into 2d physics using the Godot three game engine it's not a part of our ongoing Godot 3 tutorial series now quick reminder I've probably told you this many times already but I also have a book in development and all patrons are getting the chapters as I developed them hopefully have enough for presale very soon now that I'm done the 2d stuff I'm gonna probably make that bundle available anytime now so do look for that link down below and tell all my patrons once again thank you very much for your ongoing support and thanks all of you for sticking in through this series so hopefully you'll learn something today specifically about 2d physics or though further ado let's jump right in and head on over to the dope game engine as soon as my mouse comes back to life there we go there you go so I created a default project basically just set up my node saved it set it as the default project and we're ready to go now when you're dealing with the physics you actually have a set of physics projects setting sorry available in your project settings over here so click project settings go on down in the left hand side here and locate physics there's common here and generally this is gonna tell you the frame way that you're gonna try and target your to run your physics engines at so you're gonna have updating at 60 times per second if this is slowing down or you're not hitting that target you can decrease this amount and be a little bit less intensive for your simulation where you're mostly consider concerned with though are these 2d settings right here a lot of this really doesn't matter to play around with this one this is how if you're gonna want to have it thread-safe it could potentially be a little slower because it'll be blocking well threads are updated you could try for multi-threaded you're just gonna have to make sure that your code is thread aware but you could get better performance out as a result well that's an optimization thing to work B for later on down the road well you're probably most relevant here for size in order for settings is this guy right here and this guy right here so basically physic units in the Godot game engine for 2d physics are all in pixels at least by default and what you've got here your default gravity here is 98 that means that gravity applies at 98 pixels per second of evaluation same way as in real life gravity is 9.8 meters per second that you fall at the next one that's important here this is your gravity vector so you're falling in the l1 directory so basically you're falling along the y axis so every you can think about this in a really simplistic way every second 98 is going to be added to your y-coordinate until you're off screen and out of the simulation so if you want to change that you want to change the speed you also want to change how fast linear acceleration and angular acceleration dampen off you can do global settings here you can also decrease and increase your gravity at a global setting right here all right so that's it for settings generally the defaults are okay but you want to be aware of that they're there and with a further let's jump in the very very simple example and let's just make an object in our game world and have some gravity applied to it so we're really lying we're relying heavily on our notes based system as you pretty much everything in Godot does and what we want to create as our parent class is a rigidbody now do be careful you pick the 2d version of it instead of the full 3d version available over there so select rigidbody now rigid body is basically a physics object that takes part in the simulation it's as physical as the simulated item gets that'll make more sense in a second when I explain the other types of bodies that are in there but basically this will be full-blown part of the simulation what the physics simulation does basically is every frame calculates how all the physics objects reacted to each other and moves them and rotates things accordingly so basically it's doing a physics simulation in the background and you have certain degrees of involvement with the physics engine you can think of rigidbody 2d as basically being the most involved object so we'll create one of those and this you'll see right away there's this warning sign right up here basically saying that you need to have a collision shape attached to it well don't bother it that quite yet because what we're gonna do first is add a sprite so this rigid body and since it's gonna be a child of the rigid body when the rigid body moves the sprite will move as well so as I said make it as a child make a type sprite like this and we'll just use our trusty Godot icon as our texture like so and you're gonna want to be really careful of the rigid body make sure you don't scale it you'll screw things up make sure you set everything with the sizing but you'll notice you're in the rigid body there are a number of different settings we'll get into them later on you'll see you can set things like mass weight friction bounce gravity scale so this is the amount that default gravity applies so if you want this thing to be really affected by gravity you can increase that if you want to be not affected at all you could turn that down to zero and then now that we've got our sprite applied so we're go ahead and now we're gonna say add another child node we want to create a collision shape again you want the 2d version of it like so and you'll know if you pick the 3d version because it'll bump you over to the 3d editor in a minute you make that mistake and you will make that mistake over and over so anyways back here we've got a collision shape now apply and you'll see it's got an error message beside it well that's because it needs to have a shape defined to it you see the shape is available down here now since our sprite is basically a rectangle or a box that's we're gonna create so right click this guy again and select new rectangle shape like so and then click that again and edit the shape and now we're basically going on eyeball it so you can see over here we're close to our extent so what we want to do is make that about 4 or 5 times more I think the value that works out really well is 50 whoa not 55 30 and 30 yeah that's good enough so you see it's about the same bounce as our underlying shape well go just slightly less let's do 25 and 25 so so there you see it's basically around our shape around our image so everything should be pretty good to go now so now that this is all hooked up and defined let's grab our rigidbody over here pick a move and we will move you right about there and save our scene and run it here you should see gravity doing its thing and it is falling it once it hits terminal velocity anyways 998 pixels per second down the screen so that's pretty straightforward that's kind of how you create a rigid body in this world now that's not the most exciting thing in the world cuz it just kind of fell and fell off the screen so let's create another type of physics body for it to actually collide with now we don't want this next one to interact in any way we don't want to be moved when it's hit we want it to stay perfectly stationary but we want it to be part of our physics simulation the nice thing is there is exactly a perfect object for this so parent this off the root node in your scene what we want to create is a static body 2d again create the 2d version like so and then what we want to do is basically create a collision shape for it so again we need to add a child node again we are going to create a collision shaped 2d and that one game will eyeball it so collision shape and the rectangle shape did I already do that no I didn't okay create a rectangle will edit it oops I picked the wrong thing all right let's do that again edit and we'll do the size at 505 see if that works and grab this guy so what a static body is is part of the simulation so the simin the physics simulation he is going to run and this guy can be collided with but it's not actually going to move in any way so there's no mass to this guy you'll notice right here all there is is friction and bounce so let's go ahead and now run our simulation and what you will see is our guy will come and hit our other object and stop yeah so that's pretty cool we got a full-blown physics engine going on now one thing you might want is to actually be able to see this guy in action well if you want to do that go up to debug and say visual now this is a bull collision shapes like so now when we run it your collision objects will actually be drawn so it's really useful for debugging exactly what happens and you even saw there it showed the collision points that just occurred so pretty cool stuff now let's go and look at some of those actual settings and what they did you've got here you've got mass and weight now those are actually interlinked weight is basically mass times gravity so if you increase mass you will see weight doubles accordingly friction is how something slides along another surface so basically think of it as the grittiness of a surface if something is a one and the other one is a one they're gonna be very sliding they're gonna slide across each other bounce is the amount of recoil that will happen basically think of this as a rubbery kind of surface so I'm gonna make this guy a 1 will keep gravity scaled the same as what it was and we'll go ahead and run this and now this basically is setting how bouncy our scene is going to be so watch now that we're bouncy we're gonna hit and then boy up we go and down we go and off our simulation calculates so pretty cool stuff another thing is you noticed it started royal rotating there actually nevermind we'll cover that off at a later point now let's actually look at a little bit of code to run when a collision actually occurs so if we want to do this we need to set a couple things up now collision on collision between physics office we can get pretty expensive especially considering the saying you have a world where you have a hundred bullets and those bullets could potentially hit a hundred other bullets you're gonna have then what ten thousand possible collision calculations that have to do so what you've got here is basically they've made it so the contact monitoring is optional so we actually want to turn that on and we're gonna report say up to one contact like so so now that we've got contact monitoring turned on we can actually fire a an event or a signal that's raised when a collision occurs so we're gonna go here to the rigid body the rigid body is selected go over to the node and then the one that we were interested in here is so you see we've got body entered body exit shape entered shape exit we'll see those later on and Sleeps change states at sleep state x changed what we're interested in is body enter basically when this collision body hits another collision body this will be fired oh and I don't have any scripts yet here let me go ahead and add a script to this guy so alright so now let's head on back over and this is the guy we want and this is where we want to hook it up and the default function name works for me so this will actually be triggered when our one body hits the other body and you'll see here we're actually being passed in the other body that we're colliding with so all we're gonna do in this particular case when a collision occurs we're just gonna print some debug information so collision with plus body get the name like so now we'll go ahead and run this and we'll keep an eye on our console as it's running so we're running down and then BOOM occlusion occurred and there you see it's had a collision with a static body 2d and a static body 2d and the static body 2d and so on and so forth so there's where you could put your custom logic to handle on collision events now let's make this a little example a little bit more fun we're basically gonna go into our process here and we're gonna make it so that every time we click the mouse we're going to apply some actual physics to our object so what we can do here is go we're gonna have to tell that where to apply the physics so what we do is impulse point equals vector to 0.0 comma rigidbody2d collusion shape 2d dot shape dot extends y div - so basically think about this as this is the coordinate within our body where we want to push it so we're gonna be pushing it from the middle bottom so we're taking half of the height of our shape and we're gonna basically poke it from the bottom instead of from its midpoint so this will cause it to spin when we actually push it think about this is like putting English on a cool ball or a cue ball when you're hitting it in pool and then now let's do some logic so if oh wait I applied this to the wrong thing just sick I wonder mine just directly MacLeish your shape all right so if input dot is mouse button pressed button left so we will go ahead and apply impulse so this is a one time little shove and we're going to apply it at the impulse point like so and now we're going to the direction of our impulse with the strength of our impulse and what we're going to do is minus 10 remember gravity is pulling us down so this is actually going to push us back up now this is a one-time jab this basically adds the amount directly to our I think it's linear velocity that it gets applied to so if we press the left mouse button we're gonna push something up and now through the power of cut and paste let's do right mouse button and now this isn't gonna make a lot of sense because we're pushing it from the bottom and we're gonna push it down but it's still just as fun okay so that should work now let's go ahead and run this here's our object dropping left-click OOP no I screwed something up non-existent type function vector in base rigidbody just a second mm-hm missed my twos one second here so two and two now let's give that a shot again hit the click and we just applied a whole lot of impulse it'll come back eventually or we'll just give it some downs alright let's play this back a little bit so let's do minus 1 and plus 1 and now we'll run that down we come click so we're applying an impulse back up like so or down and let's pull it back down with a bunch of left clicks eventually eventually oops I picked the wrong way well anyway if you get the idea behind it basically you can apply forces or apply impulses to speed up or slow down a physics body in the simulation now you're noticing where the physics body we're working with it would apply force or apply impulse we don't directly update its position we let the physics and you deal with that the more you directly manipulate the physics though sorry the position of something the more broken your physics simulation is going to be so ideally you let the physics simulation do all of the movement in the world so now let's look at a slightly simpler example what we're gonna do now is actually just show you get rid of everything by now what we're gonna do is basically show you a straight out just simple collision detection in the world so we can do is actually create a much simpler version we actually use this in our audio example if you saw earlier on we're going to be using area to tease like so so let's create one right here and then Aereo 2d also needs a collision shapes we're gonna create a child to it so add a child node this is a collision shape as well and we've been using the same shapes over and over again so let's mix them up this time so with the collision selected head on over to the inspector pick your shape and switch that out - in this case I'm gonna go with a circle and same basic premise works for circle so you go in here to edit it and you can set the radius so let's set the radius to say 30 and actually that's pretty small 75 let's do 76 alright so there you see if we've got a circle in our world let's select that guy and move that into here and now we're going to go ahead and create another area so area 2d so this one we will make it a no no yet collision shape 2d will come down here go to new we'll go over the rectangle again edit that guy out set its dimensions to 100 by 100 thousand select this guy and let's move that down here so now we're going to look at just doing this we're not even really using physics here we're just gonna be basically checking their dimensions or it's kind of like a bounding box test or a bounding circle test depending on to your ultimate physics shape there's a lot of times you'll find you just don't need full-blown physics simulation you sometimes you just need to you know check to see if two things hit each other and in that case area to DS work very well in that regard so now let's apply just some logic to our circular shape over here we're gonna go ahead and attach a script onto him and yeah that's fine and then we're just gonna set up in the process here we're going to respond to key presses so if input duck is key pressed he write self dot move local X 5 oops and then left and I'd be a minus 5 obviously and then let's repeat the same thing for up and down so so up we want to minus on the y-direction and down we want to plus on the y-direction all right so that way we can move our shape around in the scene pretty straightforward stuff and so and you notice we just went right through the other object so let's look at actually fixing that actually will show you on area and turn exit instead so I'm going to close that down we're going to select our first shape right here we'll go two nodes and you'll see we have on area entered and on area exit so it's on area entered we're going to wire that guy up here and then let's go on back for a second and exit wired that one up so and we'll just write accordingly crimp and entered and here print exit it like so and now we'll go ahead and run that and now you'll see when we overlap entered is shown down here and as we're inside of it nothing happens nothing happens nothing happens but once we're fully outside exit enter exit so that's how you can easily tell if an overlap has occurred so if you don't need any kind of a physic reaction you don't need the shape to actually stop when it hits and enter or it hits another area then you're gonna want to use an area 2d it's also a great thing for using for triggers or for you know so say you were playing you're creating a hockey game where you had a net you could implement it using an area 2d in that case it's not a full weight simulation like other physical objects a lot lighter weight to deal with but as you can see it's easy enough to do pretty accurate collisions and on top you can get much more accurate near collisions as we will see in just one second so let's shut that down and we're going to create another node here so this time is going to be a an area 2d again but this time instead of a collision shape we were going to do is go ahead and create the child node and it is a collision polygon 2d that we want so select that guy right there and you will notice again no points going on but now we have options up here so we're around our area shape 2d the specter so we can actually go ahead or build mode we can create a solid point so I can add a point right here and you'll see I'm literally drawing a shape in the world so this is my more complex physics shape object I'm not going to actually draw anything phallic right click when you're done and you can create a very arbitrary shape easily so let's take that guy move it into the simulation like so and now you'll notice the level of precision when our sphere is going around into a custom size shape enter exit and there so really fine detail you know any kind of arbitrarily shaped collision object can be simulated this way now do you keep in mind these are a more complicated test than this and this so you're only going to want to use a collision polygon when you actually need the additional amount of precision but you've got a lot of flexibility by the way you can use collision polygon we had rigid bodies and kinematic bodies which is I believe what we were going to talk about next so let's just shut that down and yep kinematic body is the next thing we're gonna talk about now kinematic body is along the same lines basically a kinematic body is kind of a compromise solution the problem with physics especially what I mentioned earlier on is when you're moving physics objects you don't want to move them directly you don't want to say X plus equals 5 that screws up the simulation it can't predict you know where the last frame or the next frame is going to be so you don't want to direct input in the problem is when you're dealing with player characters while they're responding directly to keyboard inputs keyboard presses and that's where kinematic character comes in basically what you're saying is this guy isn't controlled by the physics simulation but it fully is part it and we can we can control it with a couple of special helper objects for moving around in our world including move-ins slide and move and collide so you can do more direct place movements for your direct character so you know you're not if you ever try to use a full physics engine to simulate like a platformer good luck it's a nightmare people don't like doing things like standing still bursting in different directions just does not work well under a normal physics simulation and that's where a kinematic character generally comes in great now a kinematic character will fully collide with objects in the physics world world so we will hit a static body and be stopped by them it will hit a rigid body and be stopped by them so let's go ahead and create such a simulation so we're gonna set up a simple world to work with that's gonna involved so we've got a node here so I think we're just gonna create all static bodies so static body 2d should be here somewhere there it is alright so let's create our floor so collision shape new child node so that is a collision shape and that will be a rectangle so let's edit out that rectangle this and make that guy 605 all right so there is our floor that's how I grab the static body over here and move that into our world now what I want to do next is create a wall and a ramp so let's make our wall next so static body let's create a new one new collision you should know no static body 2d like so and we're going to add a child to it and that once again is a collision shape 2d so and make that a rectangle again and this time we'll make it five by 200 all right so we have a wall just grab the parent and bring him down into the world like so and now let's make our ramp so we'll just grab this entire guy and we'll just duplicate it bring this guy over here I supply a rotation to it like so okay so we now have our physics bodies in the world now we're gonna go ahead and add our character so this is where the kinematic comes in so you want a kinematic body 2d or so so this would ultimately be your player once again we're gonna control a sprite with it it's a great a sprite let us once again use our trusty icon to control the sprite so and again it's really handy to create all your physics shapes about the origin and then move them together as a unit so let's go ahead and now create a new a collision shape 2d once again a rectangle works pretty well for this guy so rectangle shape I think what did I use 25 in the end yeah that'd work all right so we have our kinematic controller is now in the world and if I just drag him over because the whole thing obviously like this and we run our simulation not that much excitements gonna happen because this is not like a rigid body it's not full-blown part of the simulation so gravity is not being applied to it by default but it will collide with objects and shapes in our world so let's add a little bit of logic to this guy now so we're obviously going to need to add a script here so create alright now when you're controlling and updating the physics components of something instead of using the AAB 4 so when you've got like the logic part or you're handling or applying physics to an object instead of using process you should actually use a special one funk and it's physics process works exactly the same it's just part of the physics simulation instead and what we're going to do here is create move by a vector to so so if input is key pressed key left move by equals vector 2 minus 5 0 actually let's tone that down minus 2 and 0 ok and once again you can do a lot of copy and paste here enter home enter Oh oops wrong way home their home oops the hell is going wrong with my keyboard Oh paste alright so key left key right and down Oh if ya way to pay attention after you've done a bunch of copy and paste okay so if key left so we gotta go this way key right or the minus sign keep up we want to go - - and the Y and down we want to go plus 2 in the Y alright so we can now move around in four dimensions let's go ahead and run that oh I didn't actually move anything so actually I couldn't do absolutely nothing so as you can see so let's go on back over and actually add the logic to actually cause us to move and this is where one of those two special functions I just talked about came in what we want to do is call after we've set up our move vector we want to go ahead and call set so that move and collide and this one takes a vector to move by which is our move by here so now that we actually have some movement going on you'll see we can now move around in our world and the cool thing is see or hitting things like that and then like that or we can come this way and hit well I need more force so I'm slowly moving up well the forces of gravity fight against us but that is essentially how you can move a kinematic character direct and the cool thing about this and again it's very much made for platforming but you can also have a couple of special ones here so let me get that back on screen we need ooh if is on ceiling so I don't have a ceiling so we won't bother doing that so we'll just do is on floor here Flor so if we're currently on the floor well let's just print that out so this is really handy if you are actually implementing a platformer so we can see here now do the same logic and then we're not or not or not or not or not okay why did it not hit one second well I think we're always off relative by one anyway so I don't actually do here so if we're not on the floor let's apply a gravity that constantly moves us down we'll just do it else and then we'll do move and collide so and we will go back door to 0 comma 1 so we have a constant vector pulling us down if we're not currently on the floor let's go ahead and run that so now you'll see it's kind of simulating gravity and then eventually we will hit that bottom and be on the floor should be on the floor okay I'm definitely doing one thing wrong here oops sorry this was a big screw-up on my behalf actually the problem here is I was originally using move and collide and the big difference between move and collide and moving slide this movement slide is what makes is on floor true or not this needs to be called beforehand but I can't just switch this out actually need to change a couple of values first off let's reduce these values quite a bit so we're gonna move by 25 actually let's do that 20 20 20 and 20 but the big problem is move and slide I'm like move and collide actually takes a second parameter as well so the first one is the amount to move by the second value here is the direction of the floor so the problem is that didn't know where the floor was so basically I have to tell it where down is so in this case we'll go with 0 and minus 1 like so so now in theory we should go ahead and be able to run this Oh hmm contact one more time right Oh a typo like so and let's go ahead and run it now and you'll see gravity will cause us to fall I can speed things up a bit by pressing down and then still no there we go now we're on the floor go to the left and then boom we collide and go to the right okay I got to speed that up a whole lot so let's Jack these up to 50 50 50 50 and 50 yeah there we go oh I definitely have an error in my direction there all right so on the floor I'm gonna go on left now we hit and it stops us and we go right and eventually we'll hit our ramp and slowly start making our way up or I can press the uparrow and we'll do it even faster because that is basically a jump now keep in mind I have gravity pulling us down constantly - but as you can see this is how you could ultimately implement platformer behavior very very easily and quite straightforward and the cool thing is when you actually are using the slide you can also calculate your collision so let me just show you how you print if there's a collision that occurs and that is in your kinematic body will go here node wait a minute here this is actually not event-driven so I need to do it straight in my script it's right here so we'll put this down at the bottom so this is after our move and slide is being called now what we can do is go if get a slide count is greater than zero so now we can say we just collided with something Collider equals self dot get slide collision Collider and we'll just print that out like so and let me put the colon in and go ahead and run that okay definitely screwed something up here one sec I should have no idea what happened there because if I go ahead and run it again with nothing changed here we are falling to the ground and then BOOM see when I hit something it'll report back what we hit it's possible to actually hit more than one thing at a time so let's go ahead say we're hitting the floor and we're also seeing showing us on the floor and then here we are going to hit the other static body so you can use all these basically combined to do the logic of what you are currently bouncing off us the entire idea behind again the kinematic controller is for things that you want to exist in the physics world but you want to have direct control over them now one last thing we're gonna cover here and this can be a little bit confusing and I want to keep this short so I'm only gonna cover this really briefly but this is collision layers and masks now be default you've seen every single kinematic body we've looked at if we're go into the inspector you'll see they in the physics body 2d section there is a layer and a mask layer so every single thing has this so we see here the physics body has it are rigid bodies have it as well and basically the way you can think of this is this is a grid of ten nodes and this is where this collision object exists and this is where this collision object looks for collisions so you could potentially have something like bullets which will exist saying in bullet layer two so you could say okay I'm a bullet and I'm here in this layer only but then what you'll say is in masks you will turn off too and it won't look for any collisions in that so if I go ahead say with so this physics body right here I'm gonna take it out of one so we're no longer in one we don't exist in one at all and our kinematic body on the other is it exists in one but it also looks for collisions in what so now we're gonna go ahead and run this actually let me fix my I think I have a typo in my movement code yeah okay I noticed things were definitely not moving the way I intended and this would be why all right so let's change that to a 50 that to a 50 and that to a zero and now things will control the way I expect them to all right so now that we've got this guy this guy exists in the womb move the little bugger all right try it again go ahead and run that so here we see we're gonna collide as normal so boom we hit that guy boom we hit the floor so now you can see we're gonna move over but since well not in the same layer and we're not looking in the same layer we're going to go [Music]
Info
Channel: Gamefromscratch
Views: 34,472
Rating: undefined out of 5
Keywords: Godot, Game Engine, Tutorial, Physics, 2D, Kinematic, Rigid Body, Static Body, Bullet, GameDev, Game Development, GDScript
Id: vY4I5VeQbBk
Channel Id: undefined
Length: 36min 3sec (2163 seconds)
Published: Thu Jun 21 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.