Unity3D Physics - Rigidbodies, Colliders, Triggers

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up I'm Jason and today we're gonna talk about physics and unity will talk about colliders and triggers will go into rigid bodies a little bit about physics materials and then we'll write some scripts when I first started off with unity back in the three-point-something days I remember trying to build a physics based game we're building this cannon ball shooting game and getting really lost trying to figure out exactly how you do this how do you make this thing launch and what's the difference between all these things so in this video I'm gonna really try to dive into what those differences are how you set these things up and I'm gonna try to stay right to the point and then give you the source code in the source project so you can follow along and dig in if you need to now before we get started as always I just wanted to ask if this is the kind of thing that you're interested in please just share the video it helps more than anything else you can do if you really can't share it then thumbs up or subscribe or alert or any of those things are great also if you have questions about this stuff this is very beginner level stuff I expect a lot of questions just drop them down below and I will try to answer them or a lot of times other people answer them faster than I can get to them so we're gonna start this demonstration off with just an empty scene because it's a nice easy clean place to start and we're gonna create a 3d object that's a cube and this will just be a floor and I'll go to the transform right click and hit reset to just clear out that position and then we'll set the scale X and Z to 20 because I just want to have a big floor we're gonna use this to bounce things on we've got our cube set up there and notice that it has a box Collider automatically added whenever we create a new primitive using that game object and 3d object here we create one of these we're gonna get a Collider that matches except for I don't think we get one on a quad oh actually we do we get a mesh Collider on a quad I didn't expect that so we have a cube here with a box Collider and then we're gonna add a ball so we'll go to game object 3d object and sphere and again we got a Collider but this time it's a sphere Collider because we have a circle I'm gonna grab it and just move it up its W to switch to the move tool by the way if you're not on that and just move it kind of up over this thing now if you're having a hard time with that you can grab these little bars here here or here or you can use the right mouse button and WASD get into the position where you want the ball it's kind of move around like you're playing a first-person shooter and God mode and then he hit ctrl shift F with that sphere selected and you see the shadow updated if I hold right and move back they see that the ball is actually right there so I've moved the ball up over my thing and now I want to hit play and watch my ball fall to the ground right and but I'm gonna hit play and I assume it's gonna switch to my camera I'm gonna see the shadow of the ball not much else no ball is falling if I go to the scene view the ball isn't following either let's fix the camera real quick and then make the ball fall so to fix the camera we'll just grab the camera and well I can drag it up there we go now I can see in my camera preview that it's better the other thing I can do of course is just get into a position of a view that I want and maybe hold ctrl shift F and then I've got it in that view in fact why not let's stick at that view for now go to whatever view you want though if you're following along so now our cube is here and our sphere is here but they're not interacting or spheres not actually falling and the reason for this is that a Collider isn't enough to make a thing fall and if you think about it that make sense our floors have colliders on them our walls have colliders we don't want all those things moving and falling the collider and the part that moves it need to be independent and the part that moves it is the rigidbody component so we're going to click here add component just type our IG and rigidbody shows up now there are 2d versions of all of these components don't use those those won't work in the 3d system in fact well they'll work but they don't interact together so your 2d components won't interact with your 3d components and vice-versa you can't have 2d and 3d stuff going at the same time they're just not going to interact with each other at least not using those components so now we've got a sphere setup and we've added the rigidbody and I haven't changed any of these default values we don't want is kinematic on we do want is gravity on because we want it to fall with gravity and we'll just leave everything else as is for now and let's hit play we should be able to watch our ball fall there we go our ball falls and kind of lands on the ground now I'm gonna change this up just a little I'm gonna stop playing and I'm gonna take my scene view here and drag it to be off to the side of the game view just so I can kind of see them side by side when I'm playing I don't do this all the time but when I'm debugging things and building samples it find it a lot easier to see exactly what's going on if I have both of these visible so we've got our sphere here and like I said it's just kind of landing on the ground it's not doing anything special it's not bouncing it's not rolling it's not doing anything really right let's let's hit play one more time and just watch it again gonna watch it but I want to get a little bit closer to the this fear at this time so if we go down here and look at this fear and see okay it's kind of landed right there and I can even grab it and drop drop it and you'll see it'll fall again it's not really rolling or anything though let me stop playing now let's take the ground here I'll select the cube and it'll just rotate the Z or the x value a little bit may I rotate them both just a little and then I'm gonna hit play and what we should see is our ball is gonna fall down and roll along so it's gonna roll kind of with the way that gravity would pull it down because I've tilted it that way you can kind of see it's down here below zero on this edge I'm gonna stop playing because I wanted to show you that for a very important reason let's reset that rotation the Z and the X and then let's hit play again let's let the ball sit on the cube and then rotate it and see what happens so here we go our ball is on our cube and we're in play mode we're still we're still running and I'm just gonna rotate this cube oops I didn't rotate it moved it grabbed the rotation and will rotate it notice that it's not updating in fact we can't even our physics system doesn't even know that this thing is changing that this system or that this Collider is moving we need to make a little change here what we need to do if we want to have a component that moves and the physics system expects it to move we need to add a rigidbody so we'll add a rigidbody to it now what's gonna happen if we hit play if you think about it for a moment I just want you to think about it for a second I'm gonna hit play and then watch there we go come and well our ball is not bouncing it's not hit it's not hitting the ground because the ground is falling and you might think like okay well how do I do this - I've locked the position do I like how do I stop this thing from following but still do this and the way that we do that is with the is kinematic check box is kinematic makes it so that the physics system isn't going to move our object but it will interact with our things so our ground will still interact but it won't be pushed around by gravity or pushed by other objects it can only be controlled by us either from tweaking things in the inspector like we're doing which we wouldn't really do in a normal situation or from code where we're rotating and encoding we'll dive into that in just a little bit so now that we have the rigidbody with is kinematic checked let's hit play one more time and then let's try tilting the rotation once the ball lands oh the ball is there and we rotate and you can see it's starting to roll in whatever direction you know gravity would bring it oh did I miss it nope just barely made it now let's talk about physics materials I want my ball to be bouncy how do I do that or maybe I want my ball to be slippery or whatever the thing is that I want to have to create a physics material I've got one here you can see it's called bouncy it even has a picture of a ball but I'm gonna show you the steps to do it to create a new physics material we go to the project view right click on any empty spot in any folder usually I create a physics material folder but we can just go right click and look for the physics material option we don't want the 2d one I'll just pick physics material and I'm gonna call this Jason's bounce I already have a bouncy one normally I name like bouncy or slippery or whatever so I've got Jason's bounce and if it's selected you'll see that we've got a friction a dynamic friction a static friction and a bounciness first thing I want to do is just crank this up q1 all of these values are from 0 to 1 and what happens is the values get combined from the physics material that we're hitting in the physics material that we have on us so if we have bouncy and bouncy and it's average what's gonna happen is it's gonna use that same value for both of them because it's gonna average them out but if we had one that's bouncy and one zero-percent bouncy it's gonna give us the 50 that mark so I'm gonna set this to 1 on bouncy and I'm gonna turn the friction down a bit I want it relatively low and then I'll select my spear and just look at the spiracle lighter here this material field it'll just take Jason's bounce I spelled bounce wrong that's terrible let's fix my bounce there you go Jason's bounce and I've assigned it to the physics material on the sphere not on the ground just on the sphere and I'm gonna hit play and just watch what happens here we go come on Boing Boing Boing Boing so you can see it kind of bounced a little bit but it died down relatively quickly now if I go back here and I change the bounce combined into maximum what's gonna happen is instead of using the zero for the ground and the one here and getting up 0.5 we're gonna get the 1 because we're gonna use whatever the biggest value is and hopefully the average minimum and maximum makes sense but I think they're relatively simple too you're gonna pick the the biggest value of the two from the materials the average or the minimum so there we go we've got a nice bouncy ball all of this is cool and all but you may have noticed down at the bottom of my screen I've got a bunch of scripts and I did talk about triggers in dealing with things in code and we're gonna do some more interesting stuff now we're gonna start writing some code to handle these interactions so instead of just bouncing and letting the physics system control it we'll bounce and do some other stuff ourselves so let's start with a simple one we're gonna start with the change color on collision script that I've written and I'm gonna open it up and the code editor that I'm using by the way is writer it's not free but it's really awesome and it's just the one that I use data today so I've decided to start doing all my videos in it because people ask me hey what do you actually use this is what I use it's a really cool editor I like it if you don't like it though don't worry about it you can use any editor and it'll work just the same you just get a little bit less of the neat little features so let's take a look at this script are on our change color on collision script is set up to be a monobehaviour so we can add it as a component to our ball and it has a method here that's marked as an event function this is a writer thing it's just like a little tooltip to let you know that hey this is a unity event if you're not familiar with it and the event is on collision enter and it takes a collision now when I type it in here for some reason it names the collision other I hate that name for it I normally rename it to collision like that but it doesn't really matter in fact if you look at it it's light gray because we're not even using it in this context in fact what we do here is whenever a collision happens with whatever object this monobehaviour is on we're just gonna call the code in this on collision inter part by the way if you can't remember the on collision inter watch I'm gonna delete this if you start typing and you just type ONC in visual studio or in writer you should start to see all of these things up here and on collision enter is the first option you just hit enter it'll pop right back up now I'm gonna undo undo undo undo just get my code back but I wanted to show you that the intellisense and autocomplete is there for a lot of these unity methods especially works well in writer but works great in Visual Studio and probably and all the other editors by now so what do we do when we have a collision first thing we do is we select a random color by calling my get random color method which just returns back a new color with a value for red green and blue that's random between zero and one which is zero and 100% for this one we return these colors they're not um zero to 255 at zero to one it's like sliding the sliders up and down in the editor or something so we get a random color and then we're getting the renderer component on this game object whatever has a renderer we're getting the material of that and setting the color of that to the randomly selected color now if you're a unity expert you might be thinking hey we should cash that renderer yeah obviously we should cache them for performance if we were gonna do this like in a real project and constantly we would want to save off this renderer maybe in the awake method and then reuse it but in this case it's not something worth optimizing so we're just getting the renderer we're changing the material palette or to this randomly selected color and when I say it's not worth amazing I mean just profile it you'll know you'll see when this kind of thing is an issue when it's happening a lot you want to cache things when it happens rarely or it's a very tiny portion of your thing don't worry about it so much so we've got this method set up we've got our script set up let's go hook it up in game so we'll go to our sphere and we're gonna add that change color on collision script to it let's just select it and I'm gonna scroll down here and I can just uh let's minimize some of these I can just drag the script right on to it or I could hit the add component and start typing and find it and it'll hit play and watch what happens there we go so every time it hits the ground you see it when it bounces it changes color this boying change in color change color exciting stuff right but that's how we get the callback on a collision so this could be not necessarily a ball hitting it could be like you launched a rocket and it hit this thing and it's supposed to make the thing fly back and do some damage and spawn a particle you could do all of that in your on collision inter I mean ideally I would make another method and call that from your on collision inter that says what you're doing but you could do that in this is kind of where you would hook in is in that on collision inter method now let's talk briefly about triggers because I said I was going to talk about collisions and triggers and there is a big difference there's a reason to use collisions versus triggers and now we're gonna go into it a trigger is just a Collider that doesn't really interact with the physics system or at least it doesn't push or get pushed by objects in the physics system so let's take a look at what that looks like I'm gonna go here and create a new game object will create another cube and I'm gonna reset the position just right click on the transform and hit reset and I'm gonna move it up just a little bit so I'll grab the Y and drag it up out of the ground I'll make it a little bit taller maybe maybe make it like three meters tall drag it up oh whoops I rotated at three meters I meant to change the scale to about three meters okay make it three by three by three that seems good so I want to have this little box that set up underneath the ball let me move it so that it's actually under the ball so the ball is gonna kind of fall on here let's just scale it up even more make it a little bit wider and a little bit wider if I hit play right now it's got a box Collider it should just kind of bounce off of that box right let's see that in action real quick there we go balances off the box and it still changes color because remember the script is on the ball it's not on that ground piece now let's stop playing let's select that box Collider and check the is trigger box and hit play and in fact I didn't need to stop playing to do that we could have done it while playing but I wanted to hit it outside just so we keep the setting and notice that the ball is kind of going away it's going in and through and just kind of disappearing so what's happening is it's going into the trigger here and not bouncing back because the trigger box is set so we could get code callbacks but we will not get those collisions now we are getting the bounce or the color change but that's happening because it's hitting the ground piece there that's when it hits there and of course if I check these trigger box off again we'll see that it starts bouncing and I can turn back on cool and all but we're not doing anything with that trigger so let's hook that up and I want to briefly talk about when we would use triggers versus collisions so a lot of the time I think it's easy to explain a collision like you hit something and you like shot something at it and you wanted to do something when it when it hits that as trigger is a little bit int'l bit different because they're usually for like when a thing gets to an area or passes a point so this could be like an area that the player goes in and suddenly the audio changes and the lights come down or some text pops up or enemies spawn it can just be a trigger area can be like a little strip on the ground that once it's walked through the first time it triggers off some spawning of NPCs and things that come out or it could be an area that every frame that you're in it or every second that you're in it you're taking damage and we do that with our code callback so let's dive into the code callbacks now and see what that looks like so I've got my cube I'm gonna name this trigger cube just so that we know then what it is the name doesn't matter at all and we're gonna take the change color on trigger enter and drop of that onto the trigger cube and then we're gonna open this up so this one's a little bit different of a script and notice the biggest difference is instead of on collision inter we use ontriggerenter let's go back and forth and this is where people mess up the most the biggest problem I've run into and seeing other people struggle with is using on collision intro when they have a trigger or using on trigger intro when they have a Collider that's not a trigger it happens all the time it's very easy to mistake and just you know accidentally type the wrong one or switch back and forth between them and get them except so if you ever run into the issue where your colliders or your triggers aren't working just do another double check that you're using the right one that using the correct trigger enter or collide or or collision enter and also make sure that you're not using the 2d ones when you want to be in 3d or if you're doing a 2d project make sure that you're not using the 3d ones so what does ontriggerenter do differently well first is we don't have a collision here so we just have this Collider which is the other thing that we hit and this is actually the collider of the other object that we land that we hit so we could access that ball here by calling something on the other or maybe changing the renderer or material of the other but that's not what we're doing instead we're just selecting a random color and we're getting the renderer again of this thing and setting the color to that random one the only real difference here is that in our random color selection we get our red green and blue at zero to one and then we set the alpha at 0.25 so that it's semi transparent or very transparent I guess let's go in and hit play and watch that in action we should see our ball fall through yep there we go now you might notice that we're not getting the transparency that's because the material that I have on this ball is the earth the cube is the default one and it's not set up to be a transparent shader so what I need to do is just change that to transparent and real really I need to do that outside of play mode because doing it in play mode just changed this instance of it but you can see what's happening now so it's going through changes and then the ball changes when it hits the ground so two separate things happening we have the trigger entering here and then the collision when we hit on the bottom now let's fix that material real quick so if we go back into our project I actually have a material I've created here named trigger to do that though you just right-click go to create choose material and we'll call this let's call Jason this trigger and then we just select instead of opaque choose transparent and we're still using that standard shader and then I can drop that onto here under that cube and then next time when the color changes its gonna change from that solid white and gray to whatever the next transparent is there we go now that we've looked at triggers briefly let's take a quick look back at the colliders because there's actually a little bit of extra info that we get on these collisions that we don't get with triggers and I want to show you what that info is and how you can use it so I've got my spear here and I've added the show debug or no I haven't let's add it now add the show debug data on collision script and with the scene view in the game view side by side I'm gonna hit play and we should see a little bit of extra info here or at least some big bright red rays you see that bright red line right there that's appearing every time we hit it that is the normal of our collision so it's telling us the angle that we collided at now we notice that we only get it on the ground we're not getting it here and I wanted to look at the script real quick and see why so if we open it up you'll see that this also has an on collision integer so if you're wondering hey can I get to collision Inter's from one game object with different scripts you definitely can in fact that's often how I'll do it so we've got the on collision inter set up here and what we're doing is drawing array with debug draw ray and the Ray is there to show this little bit of data so we have two pieces of data with this collision that are really useful at least the two that I find most useful there's the thing that we hit which is the other object which again why I hate the name for this is why I would rename this to collision the other object we can access with collision dot Collider and then this is the collider on the other object so we could read the name of the object or get the game object or get a component from it or whatever we need to do the other important info though and the stuff that we're showing here is the contacts data in the collision contacts is an array of contact points and then those contact points have the point where the collision happened and then the normal or the direction at that point is facing now you might think with this list of contacts a do we go over all of them I've almost never come up with a scenario where I needed to use anything past the first one and there's almost never anything past the first one now you could have a scenario where maybe you collided with two things at the same time again it just hasn't become a problem for me or maybe collide with the same thing at two points I mean not two different things but that it hasn't been something I usually run into normally we just look at contact zero get that point and maybe we'll do something with the normal if we want to shoot something off that direction or something else but most of the time it's the point that we'll use and then I'll do something at the point like get that point and spawn a particle there or spawn a decal there so if I wanted to do a bullet hole on the wall the contact point and the contact normal would give me the spot on the wall in the direction to face out on the wall so that my thing is actually flat and I don't know if I could decal its sideways and clipping into the wall or something weird so that's all we need for getting this data is just reading it from the collision you don't have to do anything special you just have to get it out of the collision and remember that it's there but again most of the time what I'll end up doing is saying something like collision dot collider getcomponent thing that has health dot take damage or something like that so let's go back into the project one more time because I have one final script now I have two final scripts that I wanted to show you I also added a rigidbody one because I when I like I said when I first started out I would needed to launch rigid bodies I needed to launch cannonballs and it took me a little while to figure it out it wasn't super complicated but it did take a little while so I want to show you how to do that real quick and to do that I'm gonna take my sphere and I'm just gonna add this rigidbody launcher you may have already seen the script there and watching someone actually just gonna drop this down by the ground because I don't want it to bounce really high at first and then when it starts up I'll click and we should get some force going up let's see every time I click we get a little bit more force and it goes up and up and up nothing super exciting but I wanted to show how we do that and what the code looks like and it's as simple as this we get the rigidbody component again you could probably cache this if you have have this in a real project where you're gonna be using it a lot maybe cache the rigidbody and an awake method in fact let's just do that real quick let me show you how I do that so if I was gonna cash it I would hold this selection maybe hit alt enter and hit introduce variable and I call this far underscore rigidbody and then I probably get rid of the bar here and just hit all to enter again and tell it to generate it as a field I could have of course just typed it up there just like that but I get a little bit lazy with it now I'd move this part here this getting the component this is the expensive and hard part so I'd kick that line of code cut it go up here and add an awake just type AWA and hit enter let it autocomplete paste that in and there we'd be done so now we're caching the rigidbody and we're not making that expensive slope get component call every time again in a simple demo doesn't matter if it's a thing you're not doing often probably doesn't matter but just for consistency and just remind everybody that you really should cache these things if you're using them often this is how I would do it and that's how easy it is to go out and go about caching it most of the time it's not a complicated process so the last thing I wanted to share is this little tilt control script and I really wrote that just to make it a little bit more fun to play around and just to show anybody who might be wondering well what if I want to like bounce a ball and control it until this so let's take the sphere I'm gonna drag it back up here over this this thing and then I'm gonna take the cube and add the tilt control script will drop it on it's got to tilt speed value set to 5 by the way on the sphere you may have noticed the force amount is set to 100 let me talk about that for a moment when we're adding force here on line 19 we're giving it a direction and an amount so it's a vector but it's a vector with magnitude we're giving it essentially a 100 for the Y and a zero for the X and the Z in this case we could go in any direction we could go in two things forward or whatever we want but we need to give it a good amount of force if you have a very small amount of force you're gonna see that it doesn't move at all so you're going to need to play with those values and if you notice that hey like I'm doing this not working check to make sure that you actually have values that are high enough generally in my experience force values for physics stuff tend to be you know in them in the hundreds range it's usually some number of hundreds per force that I'm adding to things so okay let's go back to the tilt control though so our tilt control script is pretty simple - it has a tilt speed it's marked private with serialized field so we can modify it in the inspector and then we get the horizontal input just by reading input.getaxis and we make it negative because when I tested it it was inverted probably just because of where my cameras at and then we rotate the transform of whatever the tilt control is on from the forward vector by an angle amount of the horizontal so whatever we read there which is really gonna be like minus 1 or positive 1 unless we're using a controller where we have some some variability or I guess what kind of ramps up to but you get the idea it's gonna be basically a direction x time dot delta time times tilt speed so jump back into here and we hit play and then this is how I can use a and D to suddenly tilt the entire world and make my ball bounce in different directions go outside the box and maybe even bounce over the box if I'm really really good at it nope I'm terrible at it but I think that you hopefully get the idea also notice that that my other box was not rotating because that doesn't have the script on it only the ground one did so these are a lot of the basics for physics if you not if you're not really sure which one to use just remember that collisions are for things that you want to to be modified by the physics system or moved by the physics system so non triggers basically colliders that are not triggers are moved by the physics system or they can interact with physics system so you like run up to a wall it's going to stop you bounce or whatever if triggers are much more useful for things like entering an area starting an event stopping an event a thing that happens while you're in an area or while a thing is in an area it doesn't have to be the player it could be anything as you saw a little ball there it could be just to count the number of times the thing goes through an area I use triggers for all kinds of different things but I also use colliders for lots of stuff I'd say most of the time though when I have code hooked up it tends to be on triggers the colliders usually don't have too much code on them or it's it's less common that they do with rigid bodies again remember kinematic means that you can move it in your own code so that's if you're gonna set up a character that you're moving around you can do it with kinematic stuff and it won't be pushed by the by the physic system it won't be moved by the physic system that's basically what it means it it can move things and it can have it can exert forces on things but it will not have forces exerted on it and then yeah just remember the code and all the fun stuff that we did here if you have questions again just remember drop them down below also special thanks to everybody on patreon and everybody who subscribes if you want to grab the source it should be down below - I think I've covered everything - other then don't forget to subscribe share and tell all your friends how awesome video is all right thanks again you
Info
Channel: Jason Weimann
Views: 85,895
Rating: undefined out of 5
Keywords: unity collision detection, unity collision trigger, unity 3d, unity box collider, game development, game development for beginners, collider, unity physics, unity3d physics, oncollisionenter, ontriggerenter, rigidbody, boxcollider, spherecollider, physics material, unity collider trigger, unity3d, unity3d college, unity3d tutorial for beginners, ontriggerexit, rigidbody.addforce, addforce, unity physics tutorial, physics tutorial, physics unity, unity kinematic
Id: dLYTwDQmjdo
Channel Id: undefined
Length: 30min 25sec (1825 seconds)
Published: Sun Oct 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.