How to Simulate Gravity in Unity

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Very clear and direct solution to the problem. I have seen comments that this style of approach can result in orbits that are not fully closed in the case of two bodies - which I have assumed is due to issues with the underlying integrator in Unity.

Two observations: (1) if you have a centralized gravity then you can take advantage of the fact that force of A on B is equal and opposite of force of B on A, instead of calculating each (2) Mathf.Pow can be easily avoided by doing distance*distance

(Disclaimer: I'm the author of the Gravity Engine asset)

👍︎︎ 3 👤︎︎ u/nbodyphysics 📅︎︎ Aug 08 2017 🗫︎ replies

I normally avoid vid tutorials because people don't bother editing them and it becomes painfully long but wow, learned a ton in just a short span of time. Great job!

👍︎︎ 2 👤︎︎ u/malaysianzombie 📅︎︎ Aug 08 2017 🗫︎ replies

Am on a very tiny screen, and honestly thought I was going to learn how to simulate gravy in Unity... ffwd'd quickly to the end, was thoroughly disappointed.

👍︎︎ 1 👤︎︎ u/timothyallan 📅︎︎ Aug 08 2017 🗫︎ replies
Captions
so while back I did a video on forces in there I had a gravity simulation in unity a lot of you guys were asking for tutorial so in this video we'll have a look at how you can implement Newton's universal law of gravity in unity and of course if you want to know more about the theory behind it you can check out the other video so let's get into it here is the basic thing with a camera some lights and a planet I got the model of the acid store and the same thing for these skybox another link for both in the description now currently on my planet I only have a mesh filter and a mesh renderer let's go ahead and add a sphere Collider as well and we also add a new component this is going to be a custom script that will handle all the fog gravitational code you could go ahead and call it planet or celestial body but gravity doesn't only work for planets gravity applies to all objects with a mass so let's instead just call it a tractor it's 2 C sharp and hit create an ad let's open it up in Visual Studio now first off we can go ahead and delete our two methods and let's instead create a method called attract this method is where the magic happens now attraction happens between two objects so as an argument that's taking another attractor which is going to be the object that we want to attract we can call this object to attract now according to Newton's law of universal gravitation there's a few things that we need in order to calculate the gravitational force between two objects the first one is the position of the two objects we'll use this to get both the distance between them and the direction to apply a force in but we'll also need the object's mass now we could of course go up here and define a mass on our own and we also use some more of Newton's laws to calculate how the objects would move after we apply forces to them but unity actually has a component built in for this sort of stuff already so don't see a reason to reinvent the wheel on this one I'm of course talking about the rigidbody component now what we need to do is just make sure that every attractor has a rigidbody component we'll call it RB and let's also make sure to mark it as public so that we can access it from another attractor if we now just save this and go into unity we of course also need to add the component so let's hit add component of type rigidbody and let's drag it into the slot on the rigidbody component we'll make sure to disable use gravity because we want to apply that on our own and here we can adjust the mass now the mass for a planet like Earth is huge and that's despite earth being fairly small luckily however we can define ourselves what unit we're using so we could just say that a massive one here equals six times 10 to the power of 24 kilograms if you're going for realism just make sure to keep the proportions right in our case here let's just set the mass to something like a thousand and of course this will also totally depend on the scale of your scene my planet is fairly big compared to the standard unity sphere so that's why I'm kind of bumping up our mass we can now go into visual studio and we can now access our mass we can also access the rigid body of the object that we're trying to attract let's store that in a variable as well of type rigidbody let's call it the RB to attract and we can just set it equal to obj to attract RB and now we're ready to do some math first off let's get the direction between the object that we're trying to attract to this object we'll do that by taking our current position and subtracting the position of the oddly object we can then store this in a vector3 called direction now in order to get the distance between the two objects all we need to do is make a float called distance and set it equal to our direction vectors magnitude in other words the length of our direction vector then we can calculate the magnitude of our force let's create a float called force magnitude and this is where Newton's central equation comes in we'll take the mass of the one object our bead mass multiplied with the mass of the audio object or be two attracted mass and we'll then divide that by the distance between them squared so square our distance will go math.pow to take a number and lift it to a power in our case we want to take the number of distance and lift it to the power two and now we can create our final force vector let's create a vector three called force and set it equal to our direction vector dot normalized and then multiply it with our force magnitude in other words we'll apply a force in the direction of our object with a strength defined by Newton's equation then in order to apply that force we'll go our be to attract dot add force and here we'll simply input a force vector now of course we aren't calling this method anywhere so currently we will see nothing happening to change that that's going and create a void fixedupdate method remember fixedupdate is called a fixed amount of times per second and we use it all of our physics code here we want to find all the other attractors in our scene I'll show you how to optimize this in a second but for now we can just use fine objects of type and we want to find all a tractors we learn create an attractors array called attractors and set it equal to the objects we found will then create a for each statement what we'll loop through all of the attractor components and we'll call each one the attractor in our attractors array and for each one of these attractors we'll call attract where the object to attract is the attractor recurrently looking at let's now try and save this go into unity select our planet drag it into the project panel to create a prefab out of it let's then duplicate our planet by going ctrl D move it over and let's do this a few times and once you have a few different planets scattered around let's try and hit play now of course we'll get a bunch of errors the reason why it is a simple mistake in our logic when we loop through all of the attractors we find we're actually also looping over our current object that means that each object is also trying to attract itself and getting the direction from point A to point a and the distance between point a and point a doesn't make too much sense so let's go in here and make sure that we check if the attractor we are looking at is not equal to this attractor well then we'll go ahead and call attract let's now try again to hit play and depending on the masses of your object this might look really cool or as boring as - if we look at the position we can see the values are actually changing it's just happening super slowly if we select all of our planets and bump up the mass by putting say another zero here then we can start to see something happening especially if we do that once more luckily we can easily control the scale of all gravitation using a symbol constant and this constant is actually already part of the equation it's called the gravitational constant or just capital G for short let's go ahead and create this in a variable let's make it a constant float we'll call it capital G and this is another one of those ridiculous numbers this one is ridiculously small we can play around with this in any way we want let's just take the base number here six point six seven four put that in here let's just move up with the decimal place a few times here and let's go down to where we calculate our force magnitude and make sure to multiply with gee we now say that going to unity and hit play and now gravitation should be happening at a much quicker rate awesome there's really not much more to it using just the system we have now we can start messing around with planets masses and adding other forces to say make a planet orbit another that's just for fun take our second planet here and scale it up a bit and let's just increase the mass here by a factor 10 if you know it play we should see that all the other planets would get drawn towards this one fairly quickly now in case you want to have huge amounts of planets I definitely recommend that you optimize it a little bit a way to do this is to avoid searching for other attractors each fixedupdate call instead let's go ahead and create a public static list of attractors and we call this our attractors then whenever an object is enabled so void on enabled we want to register this object into the attractors list so will seem to go attractors add this of course we also need to make sure to initialize the attractors array so in here we'll just add a small if statement saying if attractors is equal to null then we'll set attractors equal to a new list of attractors and then on disables so void on disable will go ahead and remove from the attractors list so let's go attractors dot remove this then then the fixedupdate code we can simply avoid this line altogether and simply loop through all of the attractors in our attractors list and I got a bunch of errors here and that's because I misspelled on enable we need to disable the D there and now great play or seen is much more performant one thing you will notice is that if you go ahead and duplicate an object it will show you a quick error the reason for that is that when an object gets duplicated you will have two objects at the exact same position and again our equation does not like that so we'll simply go in here and say that if our distance is equal to zero well then we simply want to return out of it now things are just a little bit safer and we should now be able to hit play select an object and duplicated with no problem that's pretty much it for this video if you enjoyed it make sure to subscribe so dome it's a future one also if you haven't already make sure to watch my video on forces that should hopefully give you a more deep understanding of what on here and from here I just recommend you play around with it there's lots of fun to be had with these kind of simulations I find they often lead to cool game ideas I'm that thanks for watching and I will see you in the next video thanks to all of the awesome patreon supporters who donated in July and a special thanks to hands up soon cozy brawl will goat yes pamekasan Thomas Wally stone gamer Sybok mummy Jason Lotito Deric Hughes Kirk face Tamara Phi Robert Bund and Peter Locke if your name's not on the list or make sure to include you in videos later this month and next month's as well thanks a lot guys
Info
Channel: Brackeys
Views: 329,328
Rating: undefined out of 5
Keywords: brackeys, unity, unity3d, beginner, easy, how, to, howto, learn, course, tutorial, tutorials, game, development, develop, games, programming, coding, basic, basics, C#, simulation, space, planet, planets, gravity, forces, force, gravitational, Newton, newtons law, simulations, intermediate
Id: Ouu3D_VHx9o
Channel Id: undefined
Length: 9min 23sec (563 seconds)
Published: Sun Aug 06 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.