Planet Simulation In Python - Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome to another youtube video in this video i am going to be showing you how to make a planet simulation using python now the goal of this is going to be to simulate the orbits of different planets around the sun we're going to use real astronomical values so the real mass of the sun the real distance from earth to the sun all of that type of stuff and we're going to apply the force of gravity between all of the different planets so we actually get an accurate elliptical orbit now here it does look like the orbit is circular it is not you can see i'm actually writing the distance of the planet to the sun on each planet so it's changing as we go around the orbit well this is really cool we're kind of mixing a bit of physics with python and looking at a cool simulation now i will mention that this tutorial is not designed for complete beginners you should have some knowledge of python however if you don't know anything about physics don't worry i will teach you the different physics we need to know to actually i guess perform this simulation it's not very complicated i myself am not a physics major or a physics guy and i was able to figure it out pretty quickly anyways with that said let's go ahead and get into the code after a quick word from our sponsor thanks to backtrace for sponsoring this video backtrace provides application monitoring as well as error in crash reporting for games we've all been there excited to launch a brand new video game just to be tormented by crashes bugs and an overall bad user experience backtrace wants to help limit that by providing a platform that gives game developers the best error in crash reporting with the most complete and helpful information backtrace works with any platform any engine and at any scale and provides 24 7 monitoring so you can retain more players and get better ratings backtrace helps you fix issues fast by providing accurate call stacks regression detection querying and analytics and integration with microsoft teams discord slack and more you can get started with backtrace today and manage up to 25 000 monthly errors with one month retention and 10 gigabytes of storage completely for free check it out from the link in the description and thanks again to backtrace for sponsoring this video alright so let's go ahead and get started now i will mention that right here i'm not simulating every single planet you can easily adjust the simulation to add as many planets as you would like you can even put something like stars or satellites whatever you can put any of that here because of the way we're gonna set this up however the planets i'm simulating right now are just the four closest to the sun so we have earth mars venus and mercury we're just doing that so we get a nice visual and we can see everything nice and large if you were to simulate the planets that are much further away from the sun then you're going to see all of these planets kind of smooshed really close to the sun and then the huge orbits around the sun from the larger planets if that makes sense and the planets that are much further away so this is just a nice visualization again you can adjust this however you like and i'll show you how to do that so that said let's dive into this i'm going to close this and just open up a new window here and we'll start writing some code now the first thing we do actually need to do is install pygame so if you don't already have pygame installed then just open up your terminal or command prompt depending on your operating system and type in the following command pip install pi game that doesn't work for you try pip 3 install pi game if that doesn't work for you try python hyphen m and then pip install pi game if that doesn't work try python 3 hyphen m pip install pygame and if none of those commands work i have two videos that i'll put on the screen that show you how to fix your pip command anyways i'm going to assume that you have pygame installed this is just a 2d graphics library that we're going to use for the simulation if you don't know pygame don't worry we're going to use very limited features from it and i'll talk about how all of them work so the first thing i'm going to do here is just import pygame and then i'm going to say pygame dot init just to initialize the module i'm also going to import the math module because we're going to have to use that in this code okay so continuing since i'm using pi game the first thing i want to do is set up my pi game window now to do this we need to pick a width and height in pixels for our window so i'm going to say the width comma the height in all capitals because this is a constant is going to be 800 800. you can make this whatever width and height you want but i recommend you make it square and then we're going to set up a window so i'm going to say win is equal to pi game dot display dot set underscore mode now this is just going to take in the coordinates for the size of our window so we're going to pass as a tuple here the width and the height this is going to give us what's known as a pi game surface we're going to call it the window because it's the main window that we're going to draw onto and we need to have access to this surface to be able to put something on the screen and actually see something moving around now what i'm also going to do is just set a caption for this window so pygame.display.set underscore caption now the caption is just going to be kind of the title of the window i'll show you what it looks like in one second and for this we'll just do planet simulation okay perfect so now that we have this what i want to do is create something known as the pi game event loop now this is essentially an infinite loop that's going to run the entire time that the simulation is going whenever you're working with some type of game you need some type of loop that's constantly running they can keep track of the different events that are occurring in this case the only event is going to be moving the different planets but we need to have some type of loops that the window doesn't just open and instantly close we need something keeping the program running so i'm going to make a function here and i'm going to call this main and inside of here i'm going to make a variable i'm going to say run is equal to true then we're going to say well run like this and this loop will run while this variable run is true now inside of here i'm going to get the different events that are occurring in pi game so i'm going to say for event in pygame.event.get now this is going to give us a list of all of the different events that occur so key presses mouse movements whatever now when you're coding a more complex game you're going to handle those different events however the only event that we want to handle is when the user presses the x button to close the window now that event is the following i'm going to say if event dot type is equal to pygame.quit in all capitals then all we're going to do is say run is equal to false and then outside of our while loop we're going to say pygame.quit so this is literally all we need for the event loop at least for right now what's going to happen is we're going to continually run we're going to get all of the events if one of the events that occurred was we hit the x button in the window then we are going to close the window by making run equal to false since that's going to exit our loop we're going to quit pi game and then we'll be done perfect so all we need to do here is just call this main function and now that we do this we should see a pi game window pop up and then we can close it and get out of the program safely so let's try this and there we go we get planet simulation this is the caption i was talking about you could see it kind of right here beside the little pie game logo then if i click the x button we're going to close and we are all good okay we have set up our event loop nice so now that we have done that i just want to show you how we can draw something onto the screen and kind of update the screen so let's do that so at the top of this loop here i'm actually going to set up something called a clock now a clock is essentially going to make it so the frame rate of our game won't go past a certain value i'll talk about why we need this but the idea here is that if we don't implement some type of clock so some way to synchronize our game essentially you're going to run the simulation at the speed of your computer now some people want that to happen they want it to run super fast if you're on a super fast computer and then super slow if you're on a super slow one but ideally for me i don't care about what type of processor you have i just want you to run the simulation at the same speed so it looks normal hopefully that makes a bit of sense but we can kind of regulate the frame rate and how many times our game is refreshing so the way we do that is we say clock is equal to pi game dot time dot clock and then we go here and we say clock dot tick and then we put in the number of times we want this to update per second now this does not mean you're always going to update at in this case 60 frames per second however this is the maximum that you will be able to update at so we're saying clock.tick 60 that means we're going to update this loop or run this loop a maximum of 60 times per second to ensure our game's not going too fast okay so now we have our clock and as i was saying we want to draw something on the screen so to draw something i'm going to use my window right here and i'm going to say win dot fill and then i need to pass an rgb color here that's going to be the color that i want to fill the entire window with on the screen so i'm just going to define a color let's just go with white for now and white will be equal to 255 255 255 okay so that's our rgb value for white and then i'm going to pass white inside of here and we should see in a second that we're going to get the screen actually updating and now it's going to have a white background rather than a black however i will show you if i currently run the code we actually don't get any white on the screen and the reason we don't get any white on the screen is because we're not updating the display so what i need to do is say pygame dot display dot update not clear and what this does is actually take all of the drawing actions that we've done since the last update and then kind of paste them and draws them onto the screen so what i'm doing is every loop i'm going to fill the background with white and then i'm going to update the display okay so now if i run this you're going to see that we get a white background now we don't actually want a white background i want a black one so i'm going to get rid of this i just want to show you how we fill the screen okay so let's comment these out for right now perfect so now that we've done this let's start implementing a planet because obviously we want to put some planets on the screen and to do this i'm going to make a class so i'm going to say class planet and inside of here i'm going to define an initialization i'm going to say define a knit i'm going to say self we need an x and a y now the x and the y is going to be the position that we want this planet to be on the screen we also are going to need a radius we're going to need a color and then let me just check we want to take anything else we're also going to need a mass for the planets okay so these are kind of the initialization values that we have so i'm going to say self.x is equal to x self.y is equal to y self.radius is equal to radius obviously we're going to have circular planets self.color is equal to color we might want to make our planets more detailed and have multiple colors but for now we're just going to go the single color and then the mass is going to be the mass in kilograms of this planet we're going to have to use that mass to calculate the attraction between the different planets then generate the actual circular orbit which we'll get to when we start talking about the physics now there's a few other things that we want our planets to have they're going to have to have an x velocity as well as a y velocity so i'm going to say self.underscore x of l is equal to 0 and self.y val is equal to zero now i'll explain how all of these concepts work in a second but the idea is we're going to be moving our planet in a circle and in order to move in a circle we have a velocity in multiple directions so we're going to have it in the x direction which is the horizontal direction and then in the y direction and by moving in two directions at the same time we're able to generate a circle and have kind of i don't want to call it uh centripetal force or some centripetal motion but something along those lines right we're actually moving in a circle around an object at a constant speed okay hopefully this is making sense so far another thing that i want to do here is i want to have something that says self.sun is equal to false now this is going to tell us if the planet is the sun the reason we want that is because we're going to draw the orbit of the planet moving around and i don't want to draw the orbit for the sun so i need to know if it's the sun to either draw it or to not draw it and then i'm going to have the self dot distance to sun i'm just going to make this equal to zero right now and we're going to update this value for every single planet that we have so that we know what its distance is and we can then draw that on the screen and then the last thing that i want is self.orbit is equal to an empty list we're going to use this to keep track of all of the points that this planet has traveled along so we can draw a circular orbit representing well the orbit of the planet okay again all this will start to make sense as we get into more of these concepts i'm just kind of setting up all the initialization values now a few other things that i want to do here is just write out a few constants that we're going to use for our simulation now the first constant we're going to do as a class variable in the planet class and this is going to be au now au is astronomical units and this is approximately equal to the distance of the earth to the sun now i want to use a u because it's going to simplify the math that we need to do to calculate the distance between the current planet and the sun and allow us to initialize our planets at the correct au from the sun so they're kind of the correct distance away hopefully that makes a bit of sense but 1au is equal to and i just have to copy this from my other screen 1.49.6 to the exponent 6 which is what this e6 stands for and then multiplied by a thousand and i don't actually need these in parentheses so i don't know why i had it there okay so what this is saying is we are 149 000 uh i guess this is sorry 149 million and then 600 000 kilometers that's what this stands for right here but we want this to be in meters so i'm going to multiply it by a thousand to get the distance from the sun in meters uh 1au that's what this is hopefully that makes sense again when i use the distance from the earth to the sun approximately and here we're converting this from kilometers to meters by multiplying it by a thousand okay now we also want the gravitational constant now this is not negative 9.8 that's the acceleration of gravity i actually yeah i think it's the acceleration of gravity i might be messing that up but it's something do with gravity but the gravitational constant is used in finding the force of attraction between objects which is what we want to do and g is different than the regular gravity one it is uh 6.67 and actually is 4.28 e to the negative 11. okay that's great my autocomplete is working very well there nice now the last two things we want here is a scale since we're actually going to be simulating the real values here for the orbits we can't draw them at the position that we have them at i know that's probably a confusing line but the idea is if our planet is moving at you know something kilometers per second seven kilometers per second 29 kilometers per second i can't draw my planet at a million kilometers in my pi game window i need to draw it in a kind of appropriate scale right so i'm going to have to figure out what one meter represents in terms of pixels in my pi game scale here because i'm only working with 800 pixels high and 800 pixels wide hopefully this is making a little bit of sense what i'm going to do here is say 250 divided by au is the scale now this scale essentially says that one astronomical unit is going to be about 100 pixels in my pi game program you can look at the math to figure out how that works but for now leave a comment we're going to say 1au is equal to 100 pixels okay that's kind of the scale that we're going with here so we can draw things to scale in the window and then the last thing i want is the time step and this is going to represent how much of time i want to represent in my simulation or that i want to simulate is being elapsed so the idea here is every time i update the frame i'm going to pass a certain time step and say okay i want to look at one hour of this planet's movement at a time or one day of this planet's movement at a time because i don't want to look at one second it's going to take a really really long time to simulate instead i want to look at a larger time step so what i'm going to do is say 3 600 which is the number of seconds in a uh what is this in an hour yeah i think this number of seconds in an hour and then i'm going to multiply this by 24 and that's going to give me one day okay so this is representing 1 day i think that's correct yeah okay i'm pretty sure certain that is correct this would be the number of seconds in an hour right if you go 60 times 60 i think that gives you 3 600 and then multiply that by 24 and that is the time step that we're going to be doing the simulation on so kind of one day at a time we'll be updating the planet all right hopefully i'm not confusing you guys too much i do understand this is a lot we got to go through a bunch of physics and stuff here to make this work but there you go that is a planet now the next thing i want to do is implement a draw method now this draw method just going to draw the planet on the screen so what i'm going to do is say self and then i'm going to take a window that i need to draw this planet on so the x and y for my planet as well as the x velocity and the y velocity for my planet is going to be in meters so the number of meters that i am away from the sun that's what x and y is going to represent so i need to take those values and then draw them to scale right because again i can't draw like something million kilometers or million meters away i need to draw an accurate scale in pi gain so this is where the scale is going to come in i'm going to say that my x is equal to and then this is going to be the self.x multiplied by my scale okay so it's going to be self.scale and self.scale is going to be a really really tiny number that will now take this number and bring it to scale and i'm going to say y is equal to self.y and i'm going to multiply that by self.scale okay nice now one other thing i need to do is make sure that i'm drawing all of this in the center of my screen because i haven't mentioned yet when we're talking about pie game zero zero is actually the top left hand corner so let me just quickly open the window here right here where my mouse is so top left hand corner this is 0 0. if i go all the way to the right this would be 800 0. if i go all the way to the bottom right hand corner this would be 800 800 so rather than having 0 0 in the middle which you might be used to it's the top left so i don't want to draw my stuff in the top left i want to draw it in the center so that means i need to take every single value i have i need to offset it by the center of the screen so that we draw stuff in the middle hopefully that makes a tiny bit of sense but the way we do this is we say plus and then this is going to be width over 2 and then this is going to be plus and then this is going to be height over 2 and those values are right here okay so the width and the height we could just write 400 but i'm going to do width and height so that if we change the width and the height this is going to update automatically okay so now we have our x and y and now i can actually draw this onto the screen so i'm going to say pygame dot draw dot circle and i'm going to pass the window which is where we want to draw this circle i'm going to pass the color that i want to draw the circle in so this is going to be self.color i'm going to pass the position that i want to draw it in which is going to be x y that's the center of the circle and then lastly i'm going to pass the radius so self.radius okay so now we're actually going to draw the circle on the screen when we call this draw method okay hopefully this is all making a bit of sense let's now go and actually draw a few planets and initialize some of their constants so the first planet we probably want to draw is the sun can you call this on a planet i guess it's a star again not a big physics guy but the first thing we want to draw is the sun okay so i'm going to say sun is equal to planet and we're going to pass 0 0 for its x y okay so 0 0 right here for the radius of the sun we can kind of pick whatever value we want here we're just going to be kind of randomly picking the radiuses based on the relative mass of the planets so we want the sun to be the biggest and what i have in my other program here is 30 for the radius so we'll go with that and for the color i want this to be yellow so just to make this a bit easier to read i'm going to define yellow up here and yellow actually how do you even make yellow let's look at this yellow is going to be 255 255 and 0. okay so that's the rgb value for yellow obviously that's the color we want the sun so let's now put the color as yellow and then the last thing we need to pass is the mass and the mass i need to look at my cheat sheet here because unfortunately i don't have this memorized is going to be the following let me paste this in 1.98892 times 10 to the exponent 30 and in case you're wondering this is in kilograms again we're going to use the accurate masses and astronomical units and stuff for all of these planets okay so that is the sun and for the sun we're just going to say sun.sun is equal to true because remember we have this property here that says sun and we're going to make this true so that we don't draw the distance to the sun from the sun and we don't draw the orbit for the sun which we don't need okay so now that we have this let's just see if we can draw this on the screen so let's go planets is equal to and let's make a list of all of the planets because we're going to add a few more and then inside of our loop here we're going to say for planet in planets and we're going to say planet dot draw and we're going to pass the window that we want to draw it on which is win in all capitals okay nice now we also need to make sure that we're updating the display so let's steal this here and let's put it down there okay nice so we're saying for plan implant plan.draw pygame.display.update let's see if this works fingers crossed let's run the code okay there we go we get a sun in the middle of the screen very nice that is exactly what we want all right now the next thing we want to do is draw a few more plants right so let's create earth mercury all of those okay so we're going to start with earth i'm going to say earth is equal to planet now the earth is actually going to be negative 1 multiplied by planets within all capital dot a u this is going to be the distance from the sun so we're going to put that as the x coordinate and for the y coordinate we're just going to make it 0 for right now the color of the earth is going to be blue we'll write that rgb variable in a second and then the mass of the earth actually sorry we need the radius as well let's put the radius first what was the radius of the earth i had 60 in here as the radius and then the mass of the earth is this number let me copy it in 5.9742 times 10 to the exponent 24. okay that's the mass of the earth now i will actually mention here before i continue that there isn't a great article i'm going to open it up so i can show it to you guys let me get it on my google chrome here that i'm actually inspired by making this program that has all these values already so this is the article i'll leave it in the description but it essentially implements the same thing we're going to implement here in turtle now i didn't want to do it in turtle because pie game is a lot better and it's a lot faster but if you look here all the values that i'm using are just coming from here right so like the earth mass the earth distance negative 1 times a u the sun mass just want to give credit to this article i'll leave it in the description anyways enough of that we have the distance to the sun which is this we have zero 60 in blue this is the mass and i think that's all we need for the earth right now let's now put earth inside of here and see if when we draw it we get it in an accurate position okay so let's run this and we get blue is not defined okay i forgot to do that let's define the color blue blue is going to be equal to and then i want kind of a nice light blue so i just picked one of these before it's going to be 100 149 237 this is the rgb value for kind of a lighter blue if you just want it to be regular blue then you could go 0 0 and then 255 that gives you a nice dark blue okay so let's run this now and see if this works and there we go we get the uh the earth which is you know 1au away from the sun hopefully uh that makes sense but this is how the scale is working we put it at negative 1au which means we're going to the left if we put at 1au we would have gone to the right it doesn't really matter where we start it and there we go okay so now we have the earth the next planet that i want to do let's look here is going to be mars so let's say mars is equal to a planet now the distance for mars is going to be this let me just copy it in it's going to be negative 1.524 times planet.au again we're going to put its y-coordinate at zero the radius of mars it's much smaller than earth's we're going to go with 12. it's going to be red which i'll define in a second and then the mass of mars is a little bit less than earth as well so it's going to be 6.39 times 10 to the exponent 23. now for red we need to define this now again i wanted kind of a nice looking red so i picked a custom rgb value here and this value is going to be 188 39 and 50. okay and now we have mars so now that we have mars we're going to put mars inside of here and we should now draw mars at the appropriate scale so let's look at this and we see the mars over here so notice that mars is kind of right by the border i'm fine with that but if you wanted to move everything in closer then what you would do is reduce this number right here so rather than doing 250 you would do something like 200 and you're gonna notice this is going to move us in a little bit closer so that's kind of how you can mess with things just make the number here smaller if you want everything to get closer to the sun okay so we'll go 250 au for now all right so now we have mars let's do our other planets so the other planets we have is mercury this is going to be equal to planet uh this distance this is the closest one to the sun my understanding is at least this is going to be zero we're going to have to make this smaller so we're going to go zero the color is going to be dark gray which we'll implement in a second and then the mass let me just copy this in is going to be 0.330 times 10 to the exponent 24. if we wanted to be consistent we could go 3.30 times 10 to the exponent 23 that gives us the same thing okay so let's implement dark gray now so let's go up two colors dark gray is equal to and then what did i have dark gray at let me just look here this is going to be 80 71 note 78 and 81. again you mess with these colors if you want i'm just picking some custom ones so they look a little bit nicer okay so now we have mercury so let's put mercury in here and we can just go right on to venus which i believe is next planet so we're going to say venus is equal to planet uh its distance is going to be 0.723 times a u in case you're wondering planet.au is referencing this right here just because it's inside of the planet class okay so planet.au we're going to have zero uh this is a little bit larger so we're gonna go 14. the color of this will just be a regular white and then the mass is going to be this let me copy it in 4.8685 times 10 to the exponent 24. okay let me zoom in so you guys can read that a little bit better let's now put venus in the list and let me go ahead and run this and see if we're getting all of our plants okay nice so there we go and i've just put the plants on different sides again you can kind of put put them wherever you want doesn't really matter we could put them all on the same side and have them move at the same time i'm just staggering them a bit maybe some of you will have issue with that based on your physics knowledge but this is what we're going to do for right now okay there we go we have all of our plants so now that we have all of our planets the next thing we need to do is start moving them now moving them is complicated but again as i mentioned we're going to be moving them by their x velocity and their y velocity but we need to determine what those velocities are and those velocities are determined by the force of attraction so essentially the force of gravity between the different planets all right so i'm going to start explaining the math that's going to go on here to actually move the planets around the sun and before i can do that i just want to give you a general understanding of gravity and how planets actually orbit around the sun in case you're unfamiliar so the reason why when we jump up we fall down and when we throw a ball up it comes down is because of gravity now we all know gravity but gravity is relative to different objects okay so all objects are actually attracting one another and the force of attraction that they have on one another is based on the mass of those objects now this only really becomes relevant when you have very very massive objects like planets so when we're talking about something like earth this is a massive body right is something like you know six to six multiplied by 10 to the exponent 24 kilograms or whatever the number is it's a very very massive body so relative to our mass which is maybe 60 kilograms 70 kilograms 80 kilograms whatever it is it's way way larger so it actually exerts a massive force on us that pulls us downwards towards the earth now what actually determines the strength of this force is the distance from us to the center of the earth hence why when you go up in space you have zero gravity because you're much further away from the earth now all objects again exert forces on each other and those forces depend on the two masses of the objects as well as the distance of the objects but if you're just naively looking at this equation here which is actually the force of attraction you'll see that the distance between the center of the two objects is the most important when it comes to what type of the force what type of force you're going to get because it's r squared so the further away you go exponentially the less gravity you're going to have the closer you get exponentially the more gravity you're going to get now again i'm not a physics major so take everything with a grain of salt here that's the basic understanding of gravity now when we're talking about planets we're talking about multiple massive objects that are moving around each other so when we talk about an object like earth here right the earth is moving at a constant velocity well not necessarily constant but it's moving at a relatively constant velocity around the sun now what forces it to move around the sun is gravity so the earth is already on a trajectory moving in the x direction okay so it has some speed going in the x direction and then there is a force pulling it towards the sun that force is gravity or the attraction between the earth and the sun now the reason why there's an attraction is because the sun is much much larger than the earth if the earth was larger than the sun then the sun would be orbiting around it great example if you think of the moon right the moon is much smaller than the earth it's very close to the earth and so it orbits around the uh the earth okay hopefully this is making a little bit of sense but the idea is that you have some force and that force essentially is causing the earth to move around the sun and the reason why the earth doesn't just shoot directly towards the sun like we shoot directly down on earth when we jump up is because it already has momentum moving in another direction and so there's multiple forces affecting it causing it to go in an orbit again very simplified explanation of what's going on but hopefully that makes a bit of sense now the reason i'm saying this is because we have multiple planets that are orbiting around the earth right maybe we have another planet i know i probably shouldn't have drawn it in blue but the point is there's a distance between these two planets and they also have a force of attraction on each other and that's why you're going to have different orbits and different speeds based on the location of other planets and kind of their orbital trajectory so if you have two planets here as well as a planet here well this guy's still orbiting around the sun because the sun is much larger than him but he's going to be orbiting slower than the earth is because he's not as close however the earth is going to be attracting or having some force of attraction on this planet and this planet is going to have some force of attraction on the earth and so you need to take that into account when you're actually calculating the different orbits of the planets all right i know this is a lot very very math and physics has heavy here but the idea is every single object exhibits some force on each other and we need to calculate what all of those forces are when we are actually determining the orbit so that we are going to be orbiting appropriate to where the other planets are so we can't just calculate the force to the sun we need to also calculate the force of the other planets and that's going to give us a somewhat elliptical orbit as well okay hopefully this makes a little bit of sense now let's talk about how we actually do this so as i kind of already hinted at if you look to the left of my screen you can see that i have the equation here for the force of attraction between two objects now this force is the straight line force between two objects so let me just move the earth a bit here so i can explain kind of what i mean by that and why we need to do a little bit of trigonometry so let's say we have the earth over here this we'll say is the force of gravity or the force of attraction between the two objects now to calculate this is fairly simple we just need to first calculate the distance between the two objects which we can do we then need to know the masses which we already know and the gravitational constant which we know as well so let's say we know the force well if we know the force the issue is it's giving us the straight line force we want to break this force into two components so that we are able to move the earth in an x direction as well as a y direction so we need to kind of understand this that it's giving us the straight line force we need to break that force into x and y components so we can actually move the earth around the sun in both the x and the y direction now this is the same way that we're going to calculate the distance it's very easy for us to actually find the distance because we're looking for let me just redraw all of this this right here so this is going to be r we don't know what r is but we know what the y distance is and the x distances between these two points because for both these points we have an x and a y right so we have like x 2 and y 2. so if we know both of those points we can calculate the difference in x and the difference in y and then to figure out what r is relative to our right triangle here what equation do we use well pythagorean theorem i know i completely butchered that that name but it's going to be x squared plus y squared take the root of that and that's going to give us r okay so we are able to calculate r then obviously we can take the square so once we do that we calculate the distance then we're going to calculate the force and then we need to go in the opposite direction from the force back to the x and y components okay so let's redraw this so now let's say we know the force okay and again we need to split this into x and y so we need to have i guess f x and f y now the way that we do this is we need to calculate the angle here theta because if we have any two aspects of a triangle so if we have one side length and an angle and it's a right angled triangle we can calculate any other angle or any other side length right that's just a property of a right triangle so we know f and we should know this angle and the reason we know this angle is because we know x and we know y so the way we calculate this angle is we take the arc tangent so the tan inverse of y over x now to derive why this is going to give us the angle theta let's look at the equation of tan of theta is equal to and then this is going to be the opposite over the adjacent now i like to remember this as toa okay but this is the equation you know this is a property of a right triangle so if i have tan theta is equal to the opposite over the adjacent and we're talking about this right here the opposite side length is y the adjacent side length is x and so we can kind of sub those values in right and we get y and x if we want to isolate for theta we need to take the inverse tangent so that's what we do we take tan inverse of y over x that gives us theta okay so now that we know theta we can now use theta to calculate what the f force component is or the x force component is as well as the y force component so to do that we need to use some other properties so we have a property it is so oops let me write this property so ka toa this is the way that i always remember these but we can say that the sine of theta is equal to the opposite over the hypotenuse and since we're looking for the opposite which is y we can say sine of the angle theta which we know is equal to the f of y over h h is f we know f and we're able to find what f of y is by just isolating for f of y so multiplying f by sine theta and then same thing if we want to find what fx is we can say fx is equal to this is going to be the cose of theta multiplied by f that will give us the fx component and then once we know the x and y velocity we can very easily move this around the sun all right math lesson is now over hopefully i didn't confuse you too badly again i'm trying to squeeze in what is probably taught in an entire year of grade 12 physics in about 10 minutes but that is the math that we need to understand to be able to move these objects around can't really make it much simpler than that if you don't understand basic trigonometry then i'm sure this was a lot but you can kind of just trust the properties that i showed you here and i will show you how to implement them in code if you don't understand totally fine you can still follow along and you will have a working simulation with that said let's go back to the code all right so i'm back in the code and it is time to do some math inside of code now i know we just did a lot of math but now we're doing it in code hopefully that gave you an explanation of what i'm going to write here so i'm on my planet class and i'm going to write a method that will calculate the force of attraction between another object and the current object okay so i'm going to say define attraction like that i'm going to take in self and i'm going to take in another object now the other is going to be another planet okay so the first thing i'm going to do is say that my other underscore x other underscore y is equal to other dot x and other dot y okay now the first thing we need to do here is we need to calculate the distance between the current object and the other object so let's do that we're going to say the distance in x is equal to and this is going to be the other x minus the self.x okay and then the distance in y is going to be equal to the other y minus the self-doubt one now it doesn't matter if you take the self.x and subtract it from other dot x it doesn't matter what way you do it it's going to give us the uh the magnitude which is what we which is what we want sorry because once we take the square of both these values we're going to get a positive value no matter what so i have the distance x and the distance y now i'm going to say distance is equal to and this is going to be the math dot sqrt of the distance x to the exponent 2 plus the distance y to the exponent to okay let me just check and make sure i haven't messed this up yet looks good we have found the distance okay now the first thing i'm going to do is i'm going to say if the other dot sun then i'm going to say the self dot distance to sun is equal to distance now the reason i'm doing this is because if the other object that we're calculating the force of attraction with is the sun i just calculate the distance to the sun and i just want to update the distance the sun property here so i can use that when i actually want to draw the distance of the sun on top of the planet again we're just checking is the other object the sun if it is okay we know the distance so let's just plug that in and save that value inside of the class that way we're not recalculating it later on we already have the value okay so now that we've done that we need to calculate the force of attraction so we're going to say the force uh yeah i think it's force is going to be equal to self.g we're going to multiply this by our self.mass multiplied by the other dot mass and then we're going to divide this by the distance to the exponent 2. and why did i write it like that it's going to be distance to the exponent 2 and i think that's good okay now we don't need to do any parentheses because these have the same order of operations and exponent to the exponent 2 is going to happen first anyways okay so this is how we calculate the force now remember this is the straight line force we need to break this force down into the x and to the y component which is why we have to do all of that trigonometry so now we need to calculate the angle theta so we're going to say theta is equal to and then this is going to be the math dot arc tangent of and it's actually going to be here the distance y over the distance x now the reason i'm doing a tan 2 is because this is a special function in python that's going to take the y over the x and then give us the angle associated with it so make sure you use a tan 2 from the math library if you just use a tan that's not going to work you need a tan too okay so math.810 distance x distance y now we know the angle theta now that we know the angle theta we can calculate the x velocity and the y velocity so we're going to say or sorry not the x velocity we're going to calculate the x force and the y force so we're going to say the force x is equal to this is going to be dot cosine of theta multiplied by the force okay and then the force underscore y is going to be equal to the math dot sine of the theta multiplied by the force okay and then we're going to return from here the force x and the force y okay let's break down what we did here i understand this is probably a little bit confusing still we first calculate the distance between the two objects there we go we have the distance great then what we're going to do is determine if the other object is the sun if it is we're just going to store that distance in a property here because we want to know what that value is now after that we want to calculate the force of attraction so this is the force of attraction here it's f equals m lowercase m uh over r squared multiplied by the gravitational constant g okay so that's what we're doing so self.g times mass multiplied by other mass over distance squared okay then we want to break this distance down into the two components so the uh sorry the force into the x force and the y force so we first need to calculate the angle so we say the math.arctangent2 of the distance y over distance x gives us the angle that we want then we're going to say the force x is equal to the math dot cosine of theta multiplied by force and the force y is equal to the math.sine theta multiplied by the force now remember here that all of these distances and all of these forces are real distances and forces these are actually the distances and the forces that you would see i mean it's an approximation in the real solar system so i'm not using really small pixel values in pi game i'm using massive you know meter per squared kilograms squared values whatever the units are of these forces i'm actually using the correct numbers like the large two scale numbers i just want to make that clear here because like if we were to print out what x were and print out what the force were you would see really really massive numbers because that's actually what they are in the real world because we're trying to do a simulation here okay anyway so we have attraction now that we have the force of attraction what we need to do is actually update the position of each planet based on the force of attraction between every single other planet because we can't just do it from the sun we need to look at all the other planets as i was discussing kind of in the whiteboard section so what i'm going to do is make a method here i'm going to say update position and this is going to take in itself and planets okay so what we're going to do is loop through all of the planets we're going to calculate the force of attraction between the current planet and all of the other planets we're then going to calculate what the velocity needs to be for these planets then we're going to move them by that velocity so we're going to say the total force in the x direction is equal to the total force in the y direction which is currently equal to zero and we're going to sum all of the forces together from all of the planets so we're going to say 4 planet in planets we're going to pass a list of planets here that's what we're taking in we're going to say if self is equal to planet then continue because we don't want to calculate the force with our self in fact that would just give us a zero division error because the distance between ourself and ourself is zero right so we can't do this division with the arc tangent or sorry with the distance squared that would give us an issue anyways continuing now what we're going to do is say that the force x force y is equal to and this is going to be the self dot attraction to this planet okay so again for every single planet we're going to calculate the force x and the force y that's exerting on this planet we're going to say self.attraction is equal to planet that's what's doing the calculation here that gives us the f x and fy then we're just going to sum these two variables or add to these two variables so self.x fx plus equals fx and total fy plus equals fy okay so now that we know what the total forces that's being exerted on us in the x and the y direction we need to use these forces to actually calculate what the velocity of the planet is going to be all right so the way we calculate the velocity here is we're going to say that the self.x underscore val is equal to the total fx divided by the self.mass multiplied by the self dots and then this is going to be time step now i'm going to explain how this works but this is using kind of the famous equation f equals m a okay so we have this equation f equals m a and this stands for the total force is equal to the mass divided by the acceleration now you can use this to solve for the acceleration which is what we're doing here so we're saying the acceleration is equal to f over m so i'm taking my total fx and my total mass right i'm dividing those to get the acceleration now the thing is i'm going to be adding to this i'm saying self.xfl plus equals so the way this works is i'm increasing my velocity by my acceleration multiplied by the time step there's another equation that has to do with time and acceleration to equal velocity and all those kinds of things anyways the point is though since we're simulating this over a period of time we're going to take the time step which is right here which is one day we're going to multiply that by whatever the acceleration is then we're going to take that value and add that to the current velocity now why this is going to give us a perfect elliptical is because as soon as we start going to the left or to the right of the planet and the distances and the angles change our force is going to be either negative or positive saying that we're going kind of right or we're going left or we're going up or we're going down so by doing a total summation of all of these forces what ends up happening is we go in a complete circle because by the time we get to a certain point in the orbit the velocity is going to be changing and either getting more positive or more negative moving us to the left or to the right hopefully that makes a tiny bit of sense but the point is we're going to constantly add this and you'll notice that we're not going to go faster we're just going to change in directions because what's going to happen is x velocity is going to be decreasing while the y velocity is increasing when we're at a certain point in the circle and then that's going to continually change and change directions as we move around so you'll you'll see when we start running this but that's how this works now we do the exact same thing with the y so plus equals the total fy over the self.mass okay and then multiplied by the self.time step okay so now that we have that what we need to do is just increment the x and the y because this is just the velocity so from acceleration you get velocity from velocity you get displacement or distance which is what we're now going to do so we're going to say self.x and then this is going to be plus equals self.x underscore vel and then we need to multiply this by the time step as well and then we're going to say self dot y plus equals this needs to be self.y val multiplied by self dot time step and then let's fix this to be self.expo okay and then lastly here we can actually say the self.orbit and then dot append and i'm going to append just a tuple here which is going to be self.x self.y and yeah i think that's actually good for the orbit okay so let me uh break this down one more time what we're doing is we're getting the total forces exerted on this planet from all other planets that are not itself we are then going to figure out what the x and the y velocity is using the equations i described then we are going to update the x and y position by using the velocity we need to multiply by the time step to make sure we're moving in the accurate amount of time here okay and then we have self.orbit dot append and we're appending the x and y position that we're currently at so that now we can draw the orbit for this planet which i'm going to do in a second okay so there we go we actually have all the hard stuff done now we just need to call the update position method here on all of our planets and you'll see that they'll start moving around the screen so i'm going to go to right before planet.draw and i'm going to say planet dot and then this is going to be update position and i'm just going to pass to it planets okay and that's actually all we need to start moving the planet and let's just run this now and see if it works okay so let's see and we can see that our planets are moving but we're getting a bit of an issue and i'm going to explain why that happens so first of all the reason why we're seeing our planets like thousands of times on the screen is because we need to refresh the screen by kind of redrawing a background on top of it before we draw everything again so what's happening right now is we're continually drawing the planets but we're not drawing anything on top of the old planets and so we keep seeing the old planets so all i need to do here say wind.fill and i'm just going to put inside of here 0 0 0 which is just the color black and now if i run this you're going to see that the planets just zoom towards the sun now the reason they're zooming towards the sun is because they don't have a velocity in the y or sorry in the x is the x no it's in the y direction so currently right if again if i run this you see that they just zoom right towards the sun and then keep going the reason they're doing that is because we don't have another velocity and that's what would happen if they weren't already moving in another direction so we need to apply an existing velocity in the y direction to these planets so that they will be moving around the sun so that the force attracted them to the sun causes this kind of centripetal motion or the circular motion around the planet i know this is like there's a lot of physics i wasn't actually considering how many physics i would need to explain here but the idea is for all of these planets they need some starting velocity in the y direction otherwise the only force being applied is directly x because of kind of where the planets are placed and the fact that we're just going straight down towards the sun that's the only force being applied currently because we don't have another velocity so let's apply the other velocities i'm just going to copy them in for my other screen so this is the earth velocity i'll pause so we can read them all in a second this is the mars velocity this is the mercury velocity and then this is the venous velocity okay so the earth y velocity is 29.783 this is kilometers per second multiplied by a thousand which gives us meters per second because that's what we're using excuse me the mars velocity 24.077 multiplied by a thousand again this is meters per second so kilometers then we convert to meters 47.4 for mercury and then negative 35.02 times a thousand for venus now you'll notice that for some of these we have positive uh and negative or not positive and not negative right like we have a negative planet a u moving us to the left and then we have a positive y velocity then for this one right we have a negative and positive and then here we have a positive and this actually needs to be negative to make sure that it's going to be moving in the correct direction so if you have one that's positive the other one needs to be negative so that they're all moving in the same direction vice versa hopefully that makes sense but you'll see here when this starts running okay so let me actually just run this now and we should see that they orbit so let's have a look okay so there we go now we have an orbit obviously doesn't look as cool we're not drawing the orbits but notice that they're all moving in the same direction and obviously the ones that are closer to the sun are moving faster perfect so the simulation seems to be working okay so let's now draw the orbits around and the way that we're going to do that is we're going to use all of the points that we're storing in this orbit list because every time that we call this we're going to add a point to the orbit list and we're going to draw them so what i'm going to do is add something here and say 4 point in self.orbit and i actually want to draw this yeah i'll draw this before i draw the circle i'm going to say xy equals point uh and then i'm going to say x is equal to x multiplied by self.scale and then this is going to be plus width over 2. and then i'm going to say y is equal to y multiplied by self dot scale plus height over two and then we are going to actually store these in an updated points list we're gonna say updated points equal this updated points dot append point and then we're going to draw all these points as a line so we're going to say pi game dot draw dot line and is it lines let me just have a look here to see actually exactly what we need to drew to do so this is actually going to be lines sorry we're going to pass win we're going to pass self dot color we're going to pass false which means this is not an enclosed line so we're not going to draw an ending line essentially and then we're going to pass the updated points and we'll pass a thickness of two okay let me explain what i did i understand i kind of just went through this without any explanation so what i'm doing is i'm getting a list of updated points which are going to be all of the x y coordinates to scale right so i need to get them to scale otherwise i can't draw these properly so i take them i do what i need to do to get them to scale exactly what i did right here and then i update i make a new list here updated points and append sorry not the point the new xy that i made right here okay then i'm going to draw lines now what this does is it takes a list of points which is right here and it essentially just draws a bunch of a bunch of lines between the different points and it doesn't enclose them because i passed false now this is the thickness that i want to draw the lines which is going to be 2 pixels now one thing i do need to do is just put an if statement here and say if the len of self dot points is less than two actually less than or equal to two because i believe we need at least three points then i don't wanna do any of this so we're going to say actually the opposite we're going to say if yeah if a lot of points is greater than 2 so meaning that it is at least 3 then it will do this it's just confusing myself there we need at least 3 points so if the line of point's greater than 2 do all this otherwise don't do it that should give us the orbit so let's see now if we're going to get kind of the orbital ring around let's run this and planet object has no attribute points ah sorry it's not points it is orbit and i think i did this right self.orbit yes okay solve that over nice all right let's see there we go now we get the orbits being drawn as the planets are moving around very nice so i mean you can run the simulation as long as you like and see everything working now what i want to do is implement the distance to the sun just to show you that this is not a perfect circle it is actually elliptical i know it looks like a perfect circle but since the scale is so i guess small here that we're drawing this at you can't really see the ellipticalness of the orbits okay so now what i want to do is also draw that distance on top so to do that i need to initialize a font in pi game so i'm just going to say font is equal to game dot font dot sys font like that and i'm going to pass inside of here comic sans as my font and for the font size we'll just go with something like 16 so this is the font you want and this is the size okay that's how you initialize the font and then what i need to do if i want to draw the distance is i need to say first of all if not self.sun and forgot working in python so let's use the actual not because i don't want to draw the distance between the sun and the sun which is always going to be 0. so i'm going to say if not self dot sun then we'll say distance underscore text is equal to font dot render this is how you actually create a text object that you can draw i'm going to say font.render i'm going to do an f string and this is simply going to be the self.distance to the sun and then this is going to be in meters so what i can do is i can divide this value by a thousand if i want to get kilometers to make it a little bit smaller so let's do that divide by a thousand in kilometers i'm also just going to round this just so that we don't get a massive number here so let's just round this to one decimal point put that in kilometers and then we want anti-aliasing one which is the next argument and then the last argument i believe is the color that i want to draw this in which we can just make i guess it shouldn't be self.color we'll do white okay perfect so that is now the text object created again you have to use a font object to create a text object which then you can render on the screen now i want to draw it on the screen so i'm going to say win dot bullet i'm going to pass the distance text and then the position that i want to draw this at is a little bit complicated uh and also guys sorry i just realized i made a little bit of a mistake here actually no maybe this is okay the way it is when i define xy inside the for loop this might be interfering with this although it didn't seem like it was um so i guess we can just proceed but i don't like having these names shadow each other okay we'll just proceed for now but that's kind of what i was realizing and why i paused there anyways what i'm going to do is draw this at x y and we're referencing this x y here which is going to be the center of the circle now the issue is if i draw this at the center of the circle since i start drawing the text from the top left hand corner you'll see actually let me just run the code and you'll see what happens here when i do this so you'll notice that the actual the text is kind of at the bottom right of the center now that looks really ugly i obviously don't want that to be there so what i'm going to do instead is i'm going to make it so it's drawn directly in the center now to do that i need to take the x i need to subtract this from the distance underscore text dot get underscore width divided by 2. so if i take the width of the text and divide that by 2 and then subtract that from the x that shifts me to the left so i'm exactly in the middle and then same thing with the y so y is distance text i'll get underscore height over 2. okay nice hopefully that is all clear now i'm just going to take all this and we're going to put this below when we're drawing the circle so that it gets drawn on top and we don't have any overlap or we don't have the circle kind of overlapping the text okay so let's close that uh you guys can pause the video if you want to have a look at this let's run the code though and let's see what we get nice okay so now we actually have the uh text being drawn on top and for some of the planets given it is a bit hard to see but that is all working nice so with that said i think i'm going to end this tutorial here this was a lot of stuff to go through i hope you guys appreciated this and all the math and explanations if you did please make sure you leave a like obviously you can extend this as much as you would like you can mess around with the scale you can mess around with the speed you can change the time step this is a really really flexible program and all of the hard physics and math is done so if you want to add more planets you can really easily do that this is a realistic simulation something i haven't done on the channel before and that i hope you guys appreciate all right with that said i am going to end the video again please like the video subscribe to the channel and i will see you in another one [Music] you
Info
Channel: Tech With Tim
Views: 429,771
Rating: undefined out of 5
Keywords: tech with tim, planet simulation in python, how to simulate planets in python, planet simulation, astronomy programming, astronomical programming, python, python simulation tutorial, pygame, how to use pygame, mass of earth, creating planets in python, how to initialize planets in python, initialize planets using real values, moving planets explanation, implementing movement physics, planet movement physics, programming planet simulation, coding planet simulation
Id: WTLPmUHTPqo
Channel Id: undefined
Length: 60min 1sec (3601 seconds)
Published: Sun Feb 20 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.