Creating a Flight Simulator in Unity3D (Part 1)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I've been playing a lot of flight simulator games lately like Ace Combat and project wingman what's happening these games have the same goal making the player feel like a badass fighter pilot but something's always bugged me about these games the flight physics are too simple these games ramp up difficulty by launching more missiles at you or by turning in tighter circles but flying is always dead simple the player doesn't need to know anything about energy or basic flight Maneuvers they just need to turn and burn I want a game that is more complex than that but what games are out there War Thunder is too grindy DCS is too nerdy one game that I've been following for a while is Tiny combat by y485 this game sits nicely in the middle of the realism Spectrum while still being accessible the player needs to understand Concepts like energy management where they don't need to worry about fiddling with trim settings or microtransactions my goal for this video is to create a flight Sim along those lines this video will cover both the basic concepts of flight as well as implementing the flight model using Unity 3D in future videos I'll add more features outside the flight model like weapons and enemy AI the results are available on GitHub right now if you want to Tinker with it or itch.io if you want to play it before we can start writing code we need to understand how a plane flies we'll examine the physics of flight using this plane and F-15 a plane flying through the air follows Newton's Law's emotion the plane remains in a steady state if all of the forces acting on it are balanced the plane will only speed up climb or turn if there is an imbalance in these forces the first forces to consider are drag and thrust when air hits the plane it creates drag and causes the plane to slow down the engines create thrust which causes the plane to speed up when drag and thrust are equal the plane flies at a constant speed drag increases quadratically with speed so going twice as fast requires four times as much thrust the next forces are gravity and lift gravity constantly pulls the plane downwards air flowing over the wing generates lift which pulls the plane upwards explaining how a wing generates a lift is outside the scope of this video but there are plenty of resources out there if you want to learn the bottom line is the wings generate lift depending on speed and angle of attack speed is of course how fast the plane is moving through the air angle of attack is the angle between the direction the plane is moving and the direction the plane's nose is pointing when gravity and lift are equal the plane flies at a constant altitude if the plane's speed is too low or if AOA is outside of the optimal range then lift becomes weaker than gravity and the plane will begin losing altitude the relationship between AOA and lift is shown in this chart for the F-15 and AOA of zero degrees produces zero lift so maintaining level flight requires a slight AOA a larger AOA creates more lift up to the point of Max lift if the AOA exceeds that point for example at 15 degrees then the lift drops and the plane stalls a negative AOA produces negative lift which pushes the plane downwards so in order to fly a plane needs to maintain a minimum speed and keep angle of attack inside a certain range the plane can deploy flaps which create even more lift at the cost of increased drag this is useful for flying at low speeds such as during takeoff and Landing the extra drag prevents the use of flaps at high speed whenever a surface produces lift it also produces a special form of drag called induced drag the more lift the more induced drag any maneuver that creates a large AOA will also create a lot of induced drag this causes the plane to lose speed limiting how much the plane can turn before it stalls the wings are airfoils that produce most of the lift a plane needs to fly at the tail of the plane are several more airfoils the horizontal and vertical stabilizers the stabilizers act like the fins of a dart and hold the plane at a steady angle just like the wings produced lift when the AOA is non-zero the stabilizers also produce lift however since these are located at the rear of the plane the lift will create a torque that turns the plane the plane turns by creating an imbalance of lift across these airfoils the imbalance is created by moving the control surfaces which alter the amount of lift generated the control surfaces on the wings are called ailerons when the aileron moves down the lift increases when the aileron moves up the lift decreases or even goes negative so when one aileron goes up and the other goes down the net effect is a torque that causes the plane to roll the control surfaces on the vertical stabilizers are called Rudders the Rudders work on the same principle they produce lift that cause of the plane to yaw left or right the control surfaces on the horizontal stabilizers are called elevators when the elevators move they create a torque that causes the plane to pitch up or down note that an F-15 is a fighter jet that doesn't use the traditional model of stabilizer and elevator This Plane actually moves the entire stabilizer to control pitch this has the same effect of changing how much lift is generated but there is no distinct control surface since it combines these two functions this is known as a stabilator when all of the control surfaces are in their neutral positions the plane is in steady flight when some of the controlled surfaces are deflected the plane turns just like Lyft the strength of the turn depends on speed they are weak at low speed and strong at high speed while control surfaces get stronger at high speed there is another factor that limits turning performance a squishy human in the cockpit when the plane turns it subjects the pilot to a G-Force that pushes them into the seat or lifts them up or pushes them side to side the g-force depends on how tight the turn is and the speed of the plane so at low speed the pilot can make fast turns without worrying about g-force at high speeds even a slight turn will create a large G-Force when flying straight and level the pilot feels one geoforce pulling them straight down which is gravity when pitching upwards the pilot feels extra geez pulling downwards this is a positive G-Force with enough positive G's a human heart can no longer pump blood upwards into the brain causing the pilot to black out in real life a fighter pilot with special training and Equipment can sustain 8 to 10 G for a brief period negative G-Force is even worse negative G forces occur when pitching downwards and will pull the pilot upwards instead of blood being pulled away from the head blood is instead forced into the head causing a much more dangerous condition called red out basically the Pilot's head explodes This Is Why Planes turn by pitching up and rarely make strong pitching down Maneuvers as far as I can tell the limit for humans seems to be about negative 4G to avoid injuries planes have a g limiter this will automatically reduce the strength of the turn if the pilot gives a large input since that would create a large G-Force for example the G limiter May limit the plane to making 8G turns even if the plane is capable of much stronger turns so at higher speeds the G limiter will be the main limit to how fast the plane can turn the most important principle of implementing flight physics is to fake as much as possible simulating airflow over each part of the plane is intractable for a real-time video game instead physics forces will be applied based on simple formulas and hand-tuned parameters this is much more performant and will keep the code base simple and understandable we'll start with a plane that only has a rigid body with gravity enabled if you're wondering why there's no landing gear it's because I was too lazy to model that now we can start writing the code to make this plane fly the first step of the update Loop is to measure the plane's current state to simplify the later parts we take measurements in the plane's local frame of reference we use trigonometry to find the AOA angle of attack is the AOA measured on the pitch axis angle of attack yaw is the AOA measured on the yaw axis the g-force is derived from the current and previous velocity with these measurements and the player's input we have enough information to update the plane state thrust is the simplest Force to implement the player sets a throttle value from 0 to 1 and we multiply that by the maximum thrust we apply that as a rigid body Force now we have a plane that can Roll Along the ground foreign [Music] [Music] implementing drag is a bit more complicated for one thing the drag property of a rigid body is not a realistic drag Behavior it's designed to be very fast to calculate but it doesn't behave anything like a real world drag this is the basic formula for realistic drag equals one-half times rho air density times velocity squared times surface area times coefficient of drag velocity is easy we take the current velocity of the plane air density and surface area are just ignored instead the plane's drag is controlled solely by the coefficient of drag which is hand tuned until it feels right drag is effectively velocity squared times a coefficient planes are designed to fly efficiently in the forward Direction there would be a lot more drag if the plane was flying belly first than if it was flying nose first so the coefficient of drag depends on which way the plane is facing relative to the airflow scale 6 is a function I wrote that is similar to Unity 3D's vector3.scale it allows us to specify a different value for positive and negative inputs so we can Define the drag coefficient to be low when going forward but High when going backwards all six directions can have different drag coefficients these are Blended together based on the direction the plane is facing the six drag coefficients are all defined by unity 3DS animation curve class the input for this curve is speed and the output is coefficient of drag this allows us to fine tune the drag Behavior at different speeds lastly the drag is increased when the player deploys air brakes or flaps these are simply extra drag values added to the forward drag Direction so the final function looks like this with drag implemented we still have a plane that can only roll on the ground but now it can slow down in order to actually fly we need to apply a lift Force this is the lift equation lift equals one-half times rho times surface area times coefficient of lift times velocity squared just like drag we ignore air density and surface area so the lift force is effectively velocity squared times the coefficient of lift the coefficient is not a constant it depends on the plane's angle of attack to model the AOA curve in unity we use another animation curve this curve takes input in degrees from negative 90 to 90 and outputs a coefficient from negative 1 to 1. at 0 degrees AOA the lift coefficient is zero at 30 degrees AOA the coefficient is one going Beyond 30 is the stall region where the coefficient begins to drop off this curve also handles negative AOA by producing a negative coefficient we add another term after coefficient of lift called lift power lift power is a pretty arbitrary force that doesn't correspond to any parameter on real planes it's just there to make hand tuning easier when velocity squared times the coefficient of lift times lift power is greater than the mass of the plane the plane will begin flying induce a drag depends on the same variables as lift so we calculate that in this function this is the formula for induced drag induce drag equals coefficient of lift squared over pi times AR times e Pi is obvious AR and E are constants related to the shape of the wing so instead of dividing by these values we multiplied the coefficient of lift by a hand tune parameter this function is used to provide vertical lift for the wings and horizontal lift for the stabilizers Wing lift is calculated using the parameter's angle of attack and Vector 3. right to provide lift in the correct direction the vertical stabilizers use angle of attack yaw and Vector 3. up the vertical stabilizers have their own lift power and animation curves I use the function vector3. project on plane to find the part of velocity that flows directly over the wings the idea is that air flowing sideways across the wing reduces the amount of lift so we approximate that by projecting the airflow Vector onto this plane we use Square magnitude to calculate the V squared term the coefficient of lib is calculated using the AOA curve the product of these values is the lift Force induced drag is the square of lift coefficient times the tuning parameter since this is a drag Force it's also multiplied with v squared the lift force is applied perpendicular to the airflow and induced drag is applied opposite the airflow lift and induce drag are both Force vectors so we've returned their sum the calculate lift function is called like this flaps deployed is a Boolean property controlled by the player the extra lift from flaps is implemented by increasing the lift power and AOA by hand-tuned amounts the sideways lift generated by the vertical stabilizers is also applied here note that this lift is only used to change the plane's velocity we calculate torque created by the router separately so what is a good value for Lift Power obviously zero lift power will result in zero lift through trial and error I found that a lift power of 150 is good our plane can now take off and fly unfortunately it is still not capable of maneuvering [Music] in real life the control surfaces on a plane create lift that torques the aircraft into a new orientation the result of a control input can be quite complex changing the plane's orientation will affect how all surfaces produce lift even if they are in a neutral position for example giving a yaw input is supposed to rotate the plane around the vertical axis however the rudder is located above the center of our Mass so the lift Force produced by the rudder will also create a slight roll torque small interactions like this can make the plane more difficult to fly but more importantly it makes the plane more difficult to implement the solution is to fake it since we aren't simulating individual surfaces we don't have to worry about any input causing an unintended change we simply apply a torque directly to the plane's Center of mass this gives us control over a few things for each axis we can specify a turn rate in degrees per second we also get perfectly stable flight so the plane only turns according to player input and the plane stops turning when the player releases the input this function calculates the rotation for a single axis it calculates the torque needed to reach the target angular velocity which is limited by the plane's turn acceleration and avoids overshooting the target here we turn the player's input into a Target angular velocity control input is the combination of inputs from the player pitch roll and yaw that is Multiplied with the turn rate of each axis to get the target angular velocity Target AV Target AV is limited by steering power an animation curve that reduces the strength of turn at low speeds then the torque is calculated for each axis and applied we now have a plane that is capable of taking off and maneuvering [Music] when you turn you can see the plane losing velocity from induced drag foreign [Applause] drag to zero then you get a plane that can turn without losing speed even when the engines are turned off but there's one problem when you reach high speeds you're able to make turns with more G-Force than any human could withstand the last system we need to add is a g limiter but first we need a way to estimate future g-forces the plane can measure current g-forces just by tracking the last frame's velocity but we can't measure future g-forces the same way here's the function I use to estimate GeForce it's simply the cross product of angular velocity and velocity I derived this function based on the formulas for a tangential velocity of circular motion and the g-force of circular motion from this we can derive the g-force function for the tangential velocity formula we have V tangential velocity equals angular velocity times radius for the g-force formula we have G-Force equals velocity squared divided by radius g equals V squared over r g equals V times V substitute V with the tangential velocity cancel out the r's now we are left with g equals V times AV to translate that into code using 3D vectors we've replaced the multiplication with a cross product don't ask me why that works since I discovered it by accident we also need a way to determine the G limit depending on the direction of the player's input remember that a pitch down movement has a limit of -4g while a pitch up movement has a limit of 8G we use the scale 6 function again to handle different limits depending on sign this also Blends between multiple axes smoothly SO pitching by itself will give a higher G limit than pitching and yawing at the same time we want the G limiter to work predictively across the full range of player input for example the plane at its current speed is capable of making a 16g turn and the limit is 8G the player would reach the G limit when giving an input of 50 percent that means any input above 50 would be wasted instead we want the player to reach an 8G turn at 100 input so in this example we need to multiply the player input by 0.5 to use the full range of input in general we find the scaling Factor by dividing the G limit by the maximum possible G-Force now with all of this we can write the G limiter function we calculate max input which is the player's input scaled up so that the magnitude is equal to one even if the player is giving 50 input we scale it to 100 in the same direction this is so we know what the maximum turn rate is in the direction specified by the player we get the G limit by using the function calculate G-Force limit we get the max G-Force by calculating the g-force produced if there were no G limiter if the maximum is greater than the limit we return a scaling Force the scaling force is a value in the range 0 to 1. if the G limiter returns one the plane follows the player's input without modification if it returns less than one the G limiter is reducing the turn rate the player input is multiplied by this value before calculating the Turning Force now the plane's turn rate is controlled by the G limiter preventing turns that would injure the pilot we now have a plan to implement all the basic principles of flight the next few parts will cover additional features such as HUD weapons and AI but even without those we can see the properties of real fighter jets in our simple simulation the most important property is energy energy is the sum of kinetic energy from the plane speed and potential energy from the plane's altitude every fighter pilot must learn to manage their energy properly you lose kinetic energy from drag and you lose a lot of kinetic energy from induced drag when turning when you lose too much kinetic energy you have reduced maneuverability leaving you a Sitting Duck [Music] you can convert between kinetic energy and potential energy by changing altitude climbing converts speed into altitude which stores your energy you can then convert altitude into speed by diving the only way to gain energy is from the engine's thrust another property is called Corner speed this is the speed where the plane can turn as fast as possible below this speed turned rate is limited by the strength of the control surfaces above the speed turn rate is limited by the G limiter the pilot wants to keep the plane near the corner speed to have the best dogfighting performance which means they need to manage their energy properly having too much or too little kinetic energy can lead to being outmaneuvered as the game designer we can tweak the parameters to change how the plane feels for example reducing lift and induced drag creates a plane that is much looser to fly foreign you could increase induced drag to have a plane that's fast in a straight line but loses a lot of energy when turning [Music] you can change where the corner speed is by changing the Turning strength at low speeds [Music] there are so many more aerodynamic effects that our simple simulation doesn't model but even now we have a lot of flexibility in how the plane feels you can download the code at the GitHub repo the tag part 1 is the progress up to this point you can also try out part 1 at itch.io if you like this video stay tuned for the next episode which will be released in four to six months
Info
Channel: Vazgriz
Views: 69,184
Rating: undefined out of 5
Keywords: gamedev, unity3d
Id: 7vAHo2B1zLc
Channel Id: undefined
Length: 21min 32sec (1292 seconds)
Published: Tue Sep 13 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.