Simple Physics Based Plane Controller in Unity

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to a new video and in this video we are going to make a simple plane controller mechanic thing and it's going to be entirely within the physics engine so no messing around with transforms or anything like that well we're going to use transforms but we're not going to be modifying the position of the transforms we're going to let the physics do all the movement so we'll get straight into it the first thing we need to do just for the sake of making things nice and simple to follow is we're going to go into project settings and I'm I am using the old input manager system I just haven't been able to bring myself to start learning the new one yet so and yes I know it's very simple it's literally a matter of me being lazy it's not that it's difficult I'm just lazy so what we're going to do is we are going to change the horizontal one to the horizontal axis sorry to roll and then we're going to change the vertical axes to pitch and then we're going to just copy be one of these so I'll I will copy pitch it doesn't really matter and then we're going to add one more axis at the bottom here which is if we just paste that property and then rename this one yaw and we're just going to change the values that we use from down and up to q and E so basically that just gives us another axis that we control I'm saying ax is weird that we control using the Q and E Keys exactly the same as the up and down and left and right which are now pitch and roll so we've got our plane here the plane that I'm using is a free asset from the uni asset start I will drop a link in the description obviously and the first thing we need to do with the plane is set it up so if we go up to our components for our plane and first thing we're going to add is a rigid body and then obviously we want to add a collider so obviously if you're making a proper game you wouldn't just stick a box collider on your plane you'd go a bit more into a bit more detail for the sake of building this controller we don't need the plane to be meticulously rendered in the physics engine we just need need a mass representing the plane so our box collider is just going to go from the bottom of the plane to the top of the plane and and really just cover the like the Central Mass so that's plenty for what we're doing and because we're using the physics engine to control our plane we need to set up the rigid body properly and I'm treating a single mass unit as equivalent to a kilogram so little Googling suggests that a plane about this size would be roughly 400 kilograms so that's what I'm going to set for my mass and then we also want to set our drug under angular drag to one and for now just to get things going we're going to turn gravity off we will be turning gravity back on because we use we're going to try and use the physics engine as properly as possible within my limited abilities but for now we're just going to turn it off so we can get things up and running so let's open up our scripts folder create a script that we're just going to call plane controller and there's going to be a lot of code all in one go here but I'll do my best to take it slowly and explain everything as I go to be honest it's this isn't that complicated people have been following my channel will probably grasp this quite easily so first off we need some value so we're going to start off with the public float which we're going to call throttle increment I'm guessing anyone who is interested in this video knows roughly how a plane works I'm not saying you're all Pilots but like you probably played a flight simulator but just in case anyone doesn't you don't have an accelerator in the sense that a car does where you just put your foot down and it goes you have a throttle and it's kind of like always on so like if you give it half throttle it is on a half throttle until you move that lever again so this throttle increment is going to be how much our throttle goes up or down when we're pressing the appropriate button and then we're going to need a Max throttle value which these values that I'm setting as default by the way are just values that I've messed around with and found feel right for my little plane but these are entirely changeable and as you can see the public values they're going to be in the inspector you can change them easily from within Unity I'm just giving them default values that I know feel somewhere near right so I'm just going to copy my little tool to values in here so as you can see from the tool tip throttle increment is how much the throttle moves when we press the buttons Max throttle is the maximum amount of throttle that we can have and then responsiveness is like how Twitchy the plane is like if we tilt it to the side dip it forwards backwards how quickly does it do that tipping and dipping so after that we need some values that aren't visible in the inspector these are the like the behind the scenes values so throttle is the actual amount of throttle and then roll yeah pitch or laser self-explanatory well actually sorry are these Health explanatory again I don't know how much people watching this video know about planes so I will pull up a picture in one second so yeah here's a nice little image of just young tough Wikipedia this shows the axis of rotation so roll pitching yacht is essentially the three different planes of rotation that you can have pitches kind of Dipping forwards and backwards or dipping forwards or tilting backwards rolling is exactly how it sounds roll and yeah I think it was just turning so it's just like flat turning no dipping no tilting you're just turning left and right so that's our main axis of rotation and these values here are how we keep track of that so the final value that we're going to add it here is going to be a get value and it's going to be called response modifier and all this is going to do is it's going to return RB dot Mass RB by the way we haven't you know what it's going to keep trying to work correct that so let's just add that now RB is rigid body we need to get a reference to that so it's going to return RB dot mass divided by 10 F again this is just a value that I found works and then we're going to multiply that by responsiveness so what this does is it takes the planes Mass into account when we're talking about like how the plane moves so if we just had the same responsiveness value for a plane that weighs 1200 kilograms then it's it's going to behave weirdly so the higher the responsiveness value the quicker the plane will turn and roll and pitch and you are and everything but factoring in the plane's Mass So in theory you should be able to put any massive plane in your one and then just set the responsiveness value independent of that in theory okay so that's it for our values now we need an awake and all we're going to do in the awake for now is exactly what Visual Studio is suggesting there we're just gonna get the rigid body component and then we can start writing some actual functions so our first function we're going to call Private void handle input which is going to do exactly what it sounds like it's going to do so easily enough the first three values we get are roll which is just going to equal role input dot get access roll and this is why we rename them we could have kept them horizontal and vertical it would have worked perfectly well it's just this way the names match and then I'm just going to copy that two more times and then we want pitch and Yar so that gets our rotational values then the next one is the throttle which is a little bit more involved but not particularly complicated so we're going to say so I'm going to use the space and control keys again you would set them to whatever you want and you would probably do it in a better way than me so there it could be rebound by the player in the game but I'm just going to use the keys outright because this is more about showing you how the plane mechanic Works rather than how to make a plain game so I'm just going to say get key key code dot space and if we are pressing keycode.space this is just get key so this is anytime the space bar is down throttle plus equals throttle increment else if not else false elf it else if Alpha is if get key key code dot left control and then we just go the other way throttle minus equals throttle increment now the throttle is a percentage so basically we have up here we have a Max throttle so that's actually that's poorly named that should be like Max thrust or something in fact let's do that Max rust because that's that's not a good name at all Max troll that's very misleading so our throttle is essentially a percentage of zero to a hundred of this number here of Max thrust so if throttle is 100 we get in 200 force in our engine thrust if if it's zero we're getting zero if it's 50 we're getting 100 Etc so we need to clamp this to make sure that we don't a go into negative numbers because that will cause the plane to behave very weirdly or go past our maximum thrust because if the plane has no maximum thrust it'll just shoot off into space so to do that all I'm going to do is math Earth dot clamp throttle and then just not 100 and that's the end of that function so we want our update next and all this is going to do for now is just handle inputs and then finally well not finally but finally for now we want a fixed update so I believe I've said this quite a few times on this channel anytime you're working with physics the actual physics needs to be done in fixed update and this keeps things from getting jittery and weird so we're going to add force and this wants to be transformed up forward so it's transform dot forward is forward to the plane so Vector three dot forward would be an absolute forward in the game transformed up forward is forward in relation to the plane so that's telling us which way to go and then when multiplying that by Max throttle couple and then we're multiplying that by throttle and we're not multiplying it by Max throttle because we changed it Max thrust and then we're multiplying that by throttle so that gives us our forward Force like the force imparted by the engine but Modified by the throttle amount and then next the next three values are add torque so for people who don't know add Force adds a force like whichever direction you want it will start pushing the the rigid body in that direction at torque as rotational Force so the first one is rotating around the up Axis and that's going to be times your and then times response modifier and then we'll just copy that because these are quite similar so then after that it is the right Axis and this is for pitch and then the forward axis and this is for roll so we're back in unity let's go to our plane and drag our plane controller script on here as you see these these values are already in place because I set them in the code but again if you were making a flight game that was flying a Boeing 747 these values want to be a bit different as would the ones in their rigid body but if we press play now we can see that our plane can fly uh not fly sorry tilt and move and obviously this looks quite counter-intuitive when it's uh this doesn't look very intuitive when it's sat still we can actually make it move forward which makes it look a bit more like an actual plane so one thing I'm going to do next as you can see the plane just flew off into the distance there so before we carry on I'm just going to make a little Quick Camera controller this is in no way important to this tutorial so if you're not bothered about the camera controller if you check the chapters down below you should be able to just skip past the camera controller part if you want to cheese this part just so that you can keep the camera with the plane just drag the camera into the plane object so that it becomes a child of it and then it will stay behind the plane at all times I'm gonna do something a little bit more advanced because I want the camera to sort of not 100 locking step with the plane so that you can see some movement but yeah let's say you don't need this part but if you are still with me create a script called camera controller wait for Unity to finish faffing about I'll just drag that onto the camera controller now before I forget I'll open that so I'm going to do here is create a serialized field and it's going to be an array of transforms which we're just going to call povs and then again a serialized field and this one is just going to be a float and it's just going to be speed and I think the speed is pretty self-explanatory speed is how quickly the camera will move to the position it should be in so essentially in this script all we're doing is we're saying to the camera here's where I want you to be speed is how quickly it gets there and what this does is it gives the camera a little bit of delay when you just drop the camera into the object and make it a child it's fine it follows the object around no problem but it's locked perfectly in position with that object so you kind of you can't see any movement in the object and it makes it look weird it looks like it's just like a picture stuck to the screen and the cameras flying around whereas if you let the camera follow along but have a little bit of delay you can see the movement in the plane relative to the camera and it just gives it more of a I don't know a sense of dynamicness that's a word I write for a living is definitely not a word and then we need some more values so index equals one back to three Target and obviously index is going to represent the current POV that we are looking at and Target is where we want the camera to be so let's make an update if dot get key and this time it's get key down we don't want this to be registered every single time the key is down we only want it to be registered when the key is pressed key code dot offer one so this is saying if the number one key is pressed along the top of the keyboard again you would bind these however you want index equals zero and then we're just going to copy that I'm just gonna add four in total but you could add as well I mean I guess you could add nine because there's only nine keys or ten if you want to use the zero key but or you could just have you could cycle through them maybe with the mouse scroll wheel is entirely up to you I'm just gonna add for for the demonstration purposes so that sets the index of the POV array that we're looking at and then we're just going to set the target to povs index dot position oh sorry dot position and then finally in our fixed update and I know the camera itself is not a physics object but we are following a physics object and if you try and follow the physics object in the normal update Loop what tends to happen is the physics will get updated sometimes before sometimes after the camera gets updated and then you get a horrible Jitter so if you update it in the physics update at least it remains consistent and here's a little comment to that effect so we're going to say transform dot position equals vector3 dot move towards and then we're moving from transform dot position to Target and then the amount we're going to see a Time dot Delta time times speed and then also we're going to say transform dot forward is equal to povs index.fold obviously with this one you'd probably want to make this a smooth transition rather than just snapping it to the forward position as well but like I said this camera isn't referral to this script so I don't want to spend too long on it let's go back to Unity right so we've got our camera script here speed I'm going to set to 800 and then we need four items in our array so if we go into our plane now these these do want to be childed to the plane and the reason for that is that keeps them in a relative position to the plane no matter what the plane's doing will be in that same offset relative position so all we're going to do is create some empties let's call up pov1 pov2 pov3 and pov9 nah am I kidding this for the pov1 I'm just going to stick there and then pov2 will go a little bit further back and we'll move it up and we'll tilt it down a little bit but sort of looking at the plane eov3 we will have as kind of like a cockpit view although it's not going to be a cockpit view because you can't see bugger all from this cockpit so where we'll actually put it is just above the way oh let's stick it like here I'll go with that and then finally just because it comes in handy later on in the video pov4 I'm going to stick in front of the plane looking back so let's just go up to the side a little bit and we'll spin it around so that it's facing the plane so let's just go back to our camera script and drag these in and just give that a little test run okay so our cameras moved to whatever position we had by default oh no it didn't it moved to the second one for some reason oh because I've got it set to one so yeah okay so because in the script here I have this set to one it automatically defaults to the second POV position and also I haven't changed these well that wouldn't have worked let's try that again so this is the two position this is the one position this is the oh that's not good but it's close enough and then we have this let's just tilt that one a little bit more that way and then this one will move up a little bit so one two three that's better and four yeah right and now when we start moving our camera will stay with the plane so uh one thing I've just noticed while flying around with the plane there is that I have one of these the wrong way around this should be minus transform forward so essentially transform backwards right so we've got our Basics set up the problem we have now is if we re-enable gravity on our plane and then press play obviously it drops to the floor now we can start giving it some forward force and it'll start moving forwards and you know we can give it all the thoughts and it'll start moving quite fast but we can't get off the ground we can't because gravity is pulling us down and because essentially we're a box you know you saw the collider was an actual box but also we can't turn we can't pitch we can't yeah any of that so all we need is just a little bit of lift to get off the ground and once we're off the ground the physics handles the rest of it with the engine thrust like if I if I disabled the ground now and I'll just re-enable it you can see we are actually Airborne now but we just need to get off that ground so it's quite simple to do that all we need to do is apply some upward Force um I've done very limited research like I'm not an aero Dynamics engineer or anything like that or an aerial space or an aerial plate whatever the hell the proper term for the Geniuses that do this kind of thing are my very limited research leads me to believe that for the sake of this simulation all we need to do is simulate some upward force that is kind of proportional to how fast we are moving in terms of AirSpeed AirSpeed being slightly different to just pure speed because if you're flying into a headwind your air speed would be higher even though you might still be doing 50 mile an hour for example your air speed would be higher because the wind is coming towards you so your relative speed to the air might be 80 miles an hour even though the plane is only moving 50 mile an hour so whenever the plane is more or less horizontal and apparently this accounts whether it's the right way up or upside down it will generate upward for loss as it's moving through the area enough AirSpeed so all we need to do is work out roughly what sort of speed we want our plane to be able to lift off the ground again my little bit of research suggests that this plane would probably need to get up to about 90 to 100 kilometers an hour to take off and then we just tweak the values until that's what happens so in order to do that and again this isn't strictly necessary for this tutorial but we're just going to make some little UI elements to show us our AirSpeed and things so we can make sure that our plane is taking off at the right time so let's add a text mesh Pro do a key and we're just going to lock it to the bottom corner we're not doing anything particularly Fancy with this anchor it there we don't need it to be too big 24 is probably good let's make it bold unless they're throttle none of this really matters on in this part because we're going to be setting all these values in the actual code but I just wanted to make sure everything fits so we need to make it a little bit higher let's just go with 100 200 should be let's just go 300 just to be safe okay and we'll call that element bud so let us head back into our code actually let's just save that I'm going to go to our plane controller come up to the top here and we need to get a reference to our text object so first off we need to add the TM Pro namespace there's only one p in that and then if we just come down here we'll say serialize field we don't need we don't need to be public text mesh Pro uq um we'll just call it HUD and then if we just go somewhere down here uh private void update HUD and then in here all we're going to say is HUD dot text equals bottle plus throttle dot now we're going to say test string and we're going to put this modifier F zero and the reason we're doing that is because the throttle value is a float and if you just take a float and put it to string you get like four or six decimal values and obviously we don't want that so this F tells us how many decimal values we want so in this case Zero we don't really need to know that we're doing 98.3 five six percent of throttle ninety eight percent will be fine and then finally we'll stick a little percent on the end and then we are also going to stick a backslash n on the end and that tells the text element that we want a new line because then we're going to say plus equals this could all be on one line I'm just breaking it into multiple lines because it's easier to read basically air speed plus RB dot velocity dot magnitude so this oh sorry I'm missing a missing a quotation mark so this is essentially the speed that our rigid body is moving at in unity units and then we times that by 3.6 to convert those Unity units into kilometers per hour and bearing in mind that this works because I'm treating each unit as a meter it would if you were if you wanted miles it would be different or if you were treating each unit as 10 meters or a centimeter for some reason you would need to change this number and then once again to string F0 and then this time with plus kilometers per hour and once again we need our backslash and and then finally go to dot text plus equals altitude that we don't need this one I just because it's so easy to implement I figured why not well I say easy but apparently I can't spell altitude transform dot position dot y dot two string and again F0 and then just up here in update we're just gonna say update Hood so if we go back to Unity and we need to drag our Hood object in there and give that a spin you can see that we have our throttle values and if I were to turn the gravity off so that we can fly we get our altitude as well an altitude obviously is easy because I'm treating unit units as a meter so it's literally whatever the Y value is that's the altitude above quote sea level or zero so now we know that we can start looking at our uplift Force so that we can get off the ground so back to our code and we want to go up to the top here and we want to add a new value which is going to be called public float lift and again I have a value that I found worked so I'm just going to drop that in there as a default but once again you would tweak this to suit craft like my Googling suggested that this plane needed to get up to about 95 kilometers per hour to get off the ground a Boeing 747 would need to do I think it was a 200 kilometers I want to say anyway it's not important it was more it was more than this that's that's the that's the takeaway from this it was more and then nice and simple this one we just want to go down to our Force area our fixed update where we're adding forces and we're going to say rigidbody dot add force and the force is vector3. up this time so this is universally up no matter which way we're facing the force is pushing upwards again strictly speaking this wouldn't be true all of the time as I said before it applies when the plane is sort of horizontal when it's this way around I don't again I haven't I'm not a reason I'm not a aerodynamics engineer but I don't think it would apply if it was like you know this but I'm not making Microsoft flight simulator here so vector3. up times RB dot velocity dot magnitude times lift and that is all we need to do to make it so we can get off the ground so because the lift is how do we say this because the lift applies on the plane regardless of whether we're pitching up down left right or anything we should start to take off at the speed that this number will give us which should be around 100 kilometers whether without me pressing any of the sort of controls other than the accelerator throttle here you can see we started to leave the ground a little bit after 100 kilometer kilometers per hour and then I can obviously I can start pitching upwards I can turn I can roll I can fly into the sky and crash make my camera go all weird and yeah that is pretty much it there's not really anything to answer I mean like I said there's things you could do like obviously um playing upside down apparently the problem isn't so much the wings and everything that's all fine the problem is the engines the engines aren't built to fly upside down flying straight up same problem you know there's all sorts of like tweaks like this video could easily be 50 hours long if we tried to make it anything close to like a super realistic flight simulator maybe think of this as more of a Grand Theft Auto level flight simulator but the good thing about this is that all of the controls are handled by the physics engine so you can quite easily just tweak all your rigid body values the values in this playing controller script and gear it to behave how you want it and then just as so that is basically the playing controller I'm gonna do a little bit extra you're welcome to stick around for that if you want but if you just wanted to know how to make the plane controller work the video is essentially finished so the the little bit extra I'm going to do is we're going to go into a plane control script and we're gonna add a another transform and then down in updates and because this isn't a physics object so we don't need this to be in fixed updates we're going to say propeller dot rotate vector3.write times throttle so if we go back into Unity now and in our plane we find the propeller model so I'm just going to click on it to save time it's called box o12. drag that in there and then if we press play switch to our front view for a better look we have a spinning propeller and let's not stop there we may as well give it some sound as well so we're just going to add an audio Source I have already pulled an audio from freesounds.org this is just a loop of a plane engine technically speaking if there's any plain enthusiasts out there this is a double prop engine sound so I apologize that this is going on a single prop plane but uh come on now so we wanted to play on awake and we want it to Loop and then if we go back to our code we need a reference to that so I'm just going to drop that below rigid body here audio Source engine sound and then nice and simple once again all we're going to do is another update we're just going to say engine sound dot volume equals brothel times 0.01 F so what's happening here is like you need to understand that this only works because throttle is zero to a hundred if throttle was zero to 200 0 to 135 something like that this would not work properly the audio source volume control is not to one zero one so basically by multiplying 100 by 0.01 I make it rather than not to 100 I make it not to one so when the throttle is 100 the engine is a full bar then the volume will be at full volume so let's just make sure all this works we don't need to drag anything in we've already done our audio clip let's give it a go I mean it's not the most accurate engine sound but it works oh prop looks weird when you've got the camera in the output View and that is our script so there is a bit of a weird bug with my camera scripts where it keeps every now and again rubber banding back that is just with the camera script uh and like I just threw that together to give us something nicer to look up and like let's not stress too much about that yeah I like that so that is it for this video All That Remains to do now is to thank all my amazing patreons who are as always greatly appreciated and especially with the recent dry spell that's happened the people that are still supporting me is like I very much appreciate it and of course special thanks go to the sugar daddies last momentia patreons who are Dave muldeen regreed Gabriel white Aaron Clark Mr Drunken Dragon and Andrew Hansen you guys are particularly amazing but for those of you who don't want to or don't have the means to throw anything at the patreon just know that you are also appreciated just like share send a video to a friend comment on the videos all that stuff also helps that's it for this video so hope you enjoyed it hope this video was useful we'll be coming back for the next one bye-bye
Info
Channel: b3agz
Views: 34,823
Rating: undefined out of 5
Keywords: game development, unity 3d, unity tutorial, indie gamedev, making a game, game development tutorial, game development for beginners, unity flight simulator, game development unity, game development process, unity tutorial for beginners, unity tutorial for beginners 3d, unity tutorial game, unity 3d tutorial, unity plane controller, unity airplane, unity airplane controller, unity airplane game, unity airplane physics, unity airplane controller script
Id: fThb5M2OBJ8
Channel Id: undefined
Length: 28min 43sec (1723 seconds)
Published: Fri Nov 04 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.