Collab request with @oio



Hey @oio I was wondering if you would be interested in doing a project with me or helping me do a project. It would be simulating the orbit of some celestial bodies, and would involve some physics. I've already done some research and gotten a few formulas, but still need your help with some of the implementation and math.

Advanced Collab
Interview for anyone

Fun. Ok, sure, what do you have in mind? Describe it here and I will read it and try to come up with some ideas. The more specific your reply, of course, the more useful my ideas are probably gonna be. I expect to be away from wifi for the next three hours, but will take a look as soon as i am able.


@oio This would be a game where you select the size of the body and then click to place down a few circles of that size (Each would be a random color to add some variety) and you can change the size and add more, etc. There can be more parameters you add to each planet, and we can brainstorm about what those could be, but for now I think we should focus on getting just a simple prototype working.
Then, you can play the simulation and see how the planets interact with each other. Theoretically you should be able to build functioning solar systems, binary systems, or anything (This is, of course, 2D).

Research so far:

I'm not sure if any of this is right, but some physics forms and vigilant googling have led me in this direction, so I'm semi-confident this is right.

With the simplicity of this simulation, correct me if I'm wrong, but I don't think we need to bring in Kepler's laws. All we need to know is the acceleration of each body due to gravity, and the direction in which it goes.

The acceleration is pretty easy, we just need to use and combine some of newtons laws.
Newtons universal law of gravitation (Forgive me being absolutely terrible at LaTEx)

Where G is the gravitational constant, m1 is the mass of the first body, m2 is the mass of the second body, and r is the distance between them.

And Newtons Second law:

Combined, we get our acceleration formula:

Now, this was quite easy to implement in Hopscotch. Although, I've found that because I was using "size as a %" as the mass, which was quite small numbers for this formula, you would either have to multiply each mass by a very big number (I would say around 10^7) Or make the gravitational constant, which is usually 6.125*10^-11 a lot bigger (Which is what I did, I made it 6.125*10^-2)
Without this, it would be equivalent to placing two coffee cups in space a light year apart. Nothing is going to happen.

Now, this next part is what I am having a lot of trouble with: The Direction. This is because it deals with Vectors, which I believe are an 8th grade topic (Geometry). A quick website tutorial on them gave me an idea of how they work, but this formula deals with vector positions instead of vectors, and the only descriptions of those I can find are very... scholarly.

Here is the vector formula for two bodies:

I want to focus on implementing the last one:

Because the other ones appear to involve differentials, and god knows how you would implement that in Hopscotch...

In this case, p1 is the vector position of the first planet, p2 is the vector position of the second planet, and the other variables were already introduced in the acceleration equation.

The confusion I have about the above equation is:

What exactly is a vector position in this case?

That is my research so far, please tell me what is right and wrong, or if I'm just completely off.

Now, you may see that the above equations are only for two bodies. Well, I thought it would be better to understand how to do it with two bodies before getting into an arbitrary number of planets. But, for future reference, the vector equation for multiple formulas is this:

Right now, what I'm going to try to do is implement the acceleration and vector equation and ignoring the "position" part and just using their vectors.

EDIT: Something just occurred to me... for the direction formula, will you have to actually use integration to solve it? In that case, it would be almost impossible in Hopscotch. If you actually have to solve for the direction using integration, then we can either abandon the project, use pre integrated orbital equations, or, as you said that most programs do, we can just fake it and use an approximate formula. Or, everything I have said is completely wrong and there is a much easier way to do it.


Update: Made a very simple prototype that just implements the acceleration but not direction, try making some of the objects grow or shrink and see what happens.


Sorry, I wrote a bunch of stuff and watched it vanish off the screen of my iPad just now. That will teach me to try to use this silly thing instead of a computer. Oh, well. Time to get on the laptop. :yum:


Okay, so I looked at the code you made, @BuildASnowman. Fun, huh?

I like multi-body physics problems.

Unfortunately, I think you're going to discover that, for Hopscotch, this is a problem that blows up in our faces and gets really, really, r.e...a......l..........l...............y..................... slow.

It's not that the math is complex. I mean, that's there, sure. You have to calculate the mutual force between every pair of particles, yes, and update velocities and positions. Fortunately, since it's "mutual" force between particles, or since Newton got this one right, the number of actual net force magnitudes to be calculated is only half the number that you might expect. But I said "net" force magnitudes. Each net force is made up of a sum of a potentially very large number of individual forces.

See, you do the same math, over and over, per every pair of particles. That gets you the individual forces. Then you break those forces into components (here, only X and Y, since your problem is two-dimensional) using trig. Then you calculate acceleration components from these. You use the acceleration components, in turn, to update your velocity components. Then you use your velocity components to update your particle positions.... Then you do it ALL over again.... forever! Or for as long as you want to watch stuff happen. The "show-stopper" or the "brick wall" we run into is in the growth of the number of mutual forces to be calculated.

So how many calculations are there, if you only have to deal with the mutual force between each pair? Well... can you picture the kind of "string art" that has a set of nails or pins in a board and a single string connecting each nail to each other nail? It's the same structure. The nails are the particles, and the strings are the mutual forces.

For one particle, there's nothing to calculate. No string.
For two particles, there's one force magnitude to calculate. One string.
For three particles, there are three force magnitudes to calculate. Three strings.
For four particles, there are six force magnitudes to calculate. Six strings.
For five particles... there are ten.
See what's happening?

Here's the sequence for up to 36 particles:
1 0
2 1
3 3
4 6
5 10
6 15
7 21
8 28
9 36
10 45
11 55
12 66
13 78
14 91
15 105
16 120
17 136
18 153
19 171
20 190
21 210
22 231
23 253
24 276
25 300
26 325
27 351
28 378
29 406
30 435
31 465
32 496
33 528
34 561
35 595
36 630

The formula is (N*(N-1))/2

You can calculate the next one, if you want.

My point is that to do even a relatively small number of mutually-interacting particles, you would have to do in the hundreds or thousands of force calculations. Yikes! That's just going to be painful in Hopscotch - at least on my iPad.

So what else does this entail? Well, if you don't worry about the number of calculations, or if you only do, say, five particles, the steps go like this for the simplest methods I know:

1. Find the distance between particles. That means doing Pythagoras for each pair.
2. Calculate the mutual force, according to whatever physics you're doing. If it's gravity, then it's what you've cited. G (m1*m2 )/ r^2.
3. Resolve the force into X and Y components using trig.
4. Do this for every pair of particles.
5. For each particle, add-up all the X components of force and all of the Y components of force (due to all of the other particles) separately. Call these sums "Fx" and "Fy".
6. Calculate the acceleration of each particle in each independent direction, according to Netwon's second law. Basically, ax = Fx/m and ay = Fy/m, making sure to keep up with the direction.
7. Use the components of acceleration to update your components of velocity for each particle. That's simple. vx = vx+ax*dt and vy=vy+ay*dt, where you want dt (the simulated time between calculations) to be as small as possible.
8. Use the velocity to update your position for each particle in X and Y, simply using x = x + vx*dt and y = y+vy*dt.
9. Repeat the whole mess for the entire collection of particles.

This straightforward method is the simplest to explain, but it is not the best or most accurate. Most codes use a different method, called RK4. But it's more complex.

So, how many interacting particles do you want to try to simulate in Hopscotch? :sunglasses:


@oio Thanks for the help! I want to start with 2 bodies and just see if I can get it working, and then expand to maybe 4 or 5. One question though: On step number 3, resolving it with trig, we have the force and distance, but, from what I am reading, don't we need the angle between the two points as well? And to get the angle we would need atan2, which Hopscotch doesn't have. So what do we do?

Also, I am quite curious, are you a game designer? You seem to have a lot of experience in the field of programming and game physics.


The short answer to your question, from my experience, is that you don't actually end up having to put trig functions into your code. I guess it could depend upon your language and which functions execute more quickly, but what usually happens to me is that the trig functions end up getting expressed in terms of actual distances, if you know what I mean. I'll give an example to make it more concrete.

So, like, if you wanted to know the X component of the force, and if you already knew the force magnitude, you might be tempted to say, "Now i take the force magnitude and multiply it by the cosine of the angle". But, the thing is, there is no "angle" parameter in your problem. Plus, you don't need one. And the reason is simple. See, since you have already calculated the distance between the particles, you know that the distance is treated as if it were the hypotenuse of a literal, physical "right triangle". It is the square root of the sums of the squares of the differences in the X positions and the Y positions of the particles. OK, so that means you already have the lengths of every side of that "triangle". One side has the length "abs(X2-X1) or just "dx". Normally, that would be the "horizontal" leg of the right triangle. The other leg has the length "abs(Y2-Y1)" or just "dy". That's the vertical leg, of course. By the way, it's kind of a shame that we don't have an absolute value function in hopscotch, but we can deal with that. And then, like i already said, we have to calculate the length of the hypotenuse as the square root of the sum of the squares of "dx" and "dy". The hypotenuse is what we would call "r". So, if you consider what the definition of sine and cosine functions are, you can just literally do them. They are ratios. The cosine function is dx/r. The sine function is dy/r. And so on. So, without having the angle explicitly, you have everything you need to do any trig function you want. More importantly, you have all the ingredients that you need to calculate the orbital mechanics of your particle system.

You're asking me if I'm a game designer. @BuildASnowman, I don't think you would believe me, if I told you what I am. :bust_in_silhouette: The good news is, yes, I've designed a few games. And I do physics. But more important than both of those things is that I like your questions and just want to help you do something that is going to be fun and interesting. I notice the unique people who care about the kinds of questions that you are asking. Then, I want to share just the right amount of information and to leave the rest for them to discover, so that when they are finished, they will have an understanding and a sense of accomplishment that they will, hopefully, remember and appreciate for what it is. I think that's cool. And you never know where it can lead.


I saw this image:

but aren't you saying that cos(A) = dx/r, not Fx/F?

And I also want to thank you for how kind and helpful you have been. I definitely wouldn't have gotten any of this done without you, and I sincerely appreciate how nice you have been to me.
(And I would love to hear what you do, even if I won't believe it)


Turns out... It's the same thing. Isn't that awesome?

The enjoyment is sincerely mine. I would explain why, but it would give rise to a discussion that is out of the intended scope for this web forum. Let's just say that I share whatever I have, because it wants to be shared. Few things could be more gratifying to me. I don't want to dwell on this, but I will point out the obvious. There are lots of Hopscotch users, evidently. But you are the only one asking the question. You are the only one making the effort to understand this at present. That makes you extraordinary, by any straightforward interpretation of the term. And, if it applies, then whose privilege is it, really, to be speaking with the other?

Are you currently working on a two- or three- or n-body problem? Should I create and publish something to help further? Or are you okay for now? I want to see how far you go with this. I think you will take it to successful completion.


@oio Thank you so much, that really means a lot. I'm currently working on a 2 body problem, but expanding it to three or more would be pretty easy once you just get two working. An n-body problem would be very tough just because you would have to use clones, and you can't create some new variables for every clone created because creating variables has to be hardcoded, so it seems impossible until Hopscotch adds lists. (Moral of the story: Hopscotch, add lists!)

I'm ok for now on doing this, but I might have some questions further into development. Thanks again for helping me on this!


@oio Ok, I know I said I didn't need any help, but I just implemented those equations for just one of the planets, and the planet just kind of stays still for awhile and then zips off into oblivion. I'm not exactly sure what is going wrong, could you take a look?
The text at the top is vy (And the same pattern happens with vx) Which quickly goes from near 10^-15 to 10^13... the variable names should all be the same except:
Fx is CforceX, and Fy is CForceY
R is dist


I can take a look at the code.

Typically, when something zips off to oblivion, it is because the distance between bodies has become very small. Unrealistically small. That very small distance results in an enormous force, and therefore an enormous and unrealistic acceleration, due to the fact that the force is proportional to one over r squared. As r goes to zero, the force goes to infinity! Making the problem even worse is the fact that, by the time Hopscotch gets around to doing the physics again, the position of the particle (or whatever) could be somewhere in the next galaxy. Remember how I said we want the time interval "dt" to be as small as possible? This is why.

If you were to examine the orbital mechanics game that I created, HoRiZoN, you would find that I have had to cheat in order to avoid this problem, on account of the fact that hopscotch and my iPad are just so slow. I have used an artificial upper limit on the force, and I have included energy dissipation or "drag" to keep things from going crazy. And the really frustrating fact is that I have no idea how fast or slow the game is going to run on someone else's device, because there is no absolute time reference. That is a problem with everything I create. I worry that what runs at normal speed on my slow second-generation iPad is going to be crazy fast on somebody else's device. It's a mess. And the bigger mess is that physics, such as you were trying to do here, will produce different results, depending upon how fast your processor is or how small your time intervals can be made. When I make stuff, I just get it to work on my iPad and cross my fingers for everybody else.

So, I will take a look at the code, like I said. I don't really want to "remix" and "publish" it, though. Maybe I will create a second account for remixes, in order to get around the account-clutter potential that concerns me. Either way, I will close the loop with you, unless you find the solution all on your own first. :wink:


So, @BuildASnowman, i uploaded sonething that may help. Take a look at this:

and see if it makes any sense to you. It's slow... crazy slow. I know how to make it much faster, but doing so might make it hard to see what's going on and how it all works, so i left this version plain and slow so it would be easier to read. Once you understand it, try your hand at tweaking what's there, remix and publish it. I would love to see what you can come up with. :eyes:


I would like to join but have absolutely no idea what you guys are talking about ( haven't learned a lot of physics... Yr. 4)


I would love to be able to show you what we're doing, @Isaacwotwot.

Do you know what "physics" is? It's really cool. In this discussion, @BuildASnowman and I have been talking about the part of physics that makes things like moons, planets, stars and galaxies orbit in space. I like it, but i understand that not everybody does. For those who do, we're making a little universe in Hopscotch and seeing how real we can make it. So far, we just have two planets in our universe: a lighter one and a heavier one. You could think of one as the "sun" and the other as it's "planet".

Honestly, i think you might want to read the stuff above, first, to know if it's something you're interested in. If so, then it would be fun to get your questions and ideas into it.

For those interested, welcome to our little universe! :innocent:


I really admire that you're searching up things that you're interested in @BuildASnowman. It inspires me (and makes me feel ashamed too that I haven't really bothered much to search areas I'm interested in and mean to search up in detail, like programming, chemistry and physics). I guess like you say, I like the "structure" that school has which the Internet doesn't. I was just wondering how you find learning by searching things up. I find it pretty motivational that you're doing that.

I've been making myself read absolutely everything that I encounter (on Hopscotch, at school, on the forum) and try to understand it or make sense of it, because that's how I learnt how to code on Hopscotch but this is pretty complex stuff :) and I haven't as much time either to read everything in detail (or to try and grasp anything).

Anyway I really admire too what both of you are doing @oio and @BuildASnowman and thanks for sharing your knowledge :smile:


@oio Does the optimization by any chance include mutli threading? In your HoRizOn game, it seems the velocity calculation is done at the same time and seperately from the x y calculation to increase efficiency, but in this code it seems everything depends on the previous calculation, so there would not be much point to separating it into different rules. So far I've combines some calculations and gotten rid of the need for an acceleration variable, which has helped a miniscule amount, but there seems to be one big step I can take to dramatically increase performance.


These are exactly the right questions. Way to go!

So, yes, you have noticed that part of the strategy for speeding things up in HoRiZoN was to do calculations in separate - and asynchronous! - loops. Now, @BuildASnowman, think just a sec about what that means. If the physics really want to be run the way i have it in the slow code in order to be done strictly right, what do you think the dangers could be in a parallelized (or "multi-threaded") approach, where parts of the math (for what's supposed to be the same moment in time) are being calculated asynchronously?

Also, look at anything in the clear-but-lame version that gets calculated more than once. Do you think you can consolodate those to get a faster execution? I think so.

When you have something ready to show, by all means, post it, and i'll take a look. I have a bunch of stuff that people need me to do today in another town, but i'll fit it in. Frankly... this is more fun. :blush:


@oio I think the dangers of a multi threaded approach would be that some calculations would be done with previous versions of variables, before the new ones get calculated. However, I've noticed that no blue calculations depend on the red calculations, so I think I could make it so once the "base" variables are calculated, it could trigger both the blue and red calculations to happen at the same time. My only concern is that "triggering" both the red and blue to happen at the same time and then hanging until they are both done might actually make it run slower. But I'm crossing my finger that the compiler can help me with that.