# How to orbit a moving object?

## Recommended Posts

Hi all, I've just started with BabylonJS, it's amazing and there is such a great community here!

I wanted to combine several of the playground demos into something I thought fairly simple - a basic animated model of a solar system, including moons. I'm not looking for real physics, just a conceptual model.

• objects can orbit other objects (Moons orbit planets as planets orbit the sun)
• they do so independently of those objects own rotations or spin, just their position
• potentially to any level (galaxies) - don't make a "root" object or base everything on 0,0,0
• ignoring interactions with other bodies
• circular orbits only, ignore elliptical orbits
• they can also spin on their own axis independently
• only on two axis, as solar systems are fairly flat

I started with the Lights demo and this worked fine for planets ie: light0.position = new BABYLON.Vector3(10 * Math.sin(alpha), 0, 10 * Math.cos(alpha));

• When I tried to add a moon I quickly discovered setting positions directly (ie absolute position) didn't work; positions seem to be done last and ignore any earlier translations.
• I tried setting parent objects but found that the moon would not orbit but follow the rotation of the planet around the sun - they were "tidally locked" (same face always points inwards) and not independent.
• So I used translate instead to give it an offset from the object it orbits and then try to translate local to have it spin, this *does* orbit but not from the right point, some other point in space!

I've tried messing with world and local translate and rotate, but in most cases it seems to make no difference (especially rotate acts the same) so I am confused. I would have thought a rotate world would have rotated around 0,0,0

So ultimately what I'm looking for is a method to use in the loop where I get a point in space (object being orbited) and then continue the orbit around that object, in the same directly as it had been. I fear this involves a lot of vector maths, unless there is a solution I haven't come across - ideally one that is a built-in rotational vector animation, which might not even require putting in the loop.

Thanks very much if you can offer any help!

##### Share on other sites

Hello, thank you and welcome

parenting is clearly the key to simulate a solar system. sun it the root, planets are children of the sun and so on

The best way for us to help you will be a small repro in a playground. Nothing fancy, just some code highlighting your issue

##### Share on other sites

Thanks, that was my thought too, but when I tried it didn't work as expected. I'll simplify my playground and try to replicate.

##### Share on other sites

OK here we go: http://www.babylonjs-playground.com/#1UGDQC#4

You can kind of imagine they are orbiting, but really they are just following rotation. If you uncomment the planet spin (either local or world) the moon rotates around it, as if in geostationary orbit.

Thanks!

##### Share on other sites

Cool demo!  Welcome to the forum, jb!   Here's another version...  http://www.babylonjs-playground.com/#1UGDQC#5

Good fun!  Thanks jb!  I un-parented the moon from the planet... and instead just set moo.position = planet.position in the render loop.  See that .bakeblahblahblah command, JB (line 42)?  I shifted the moon sideways for a moment... baked its current transform (which is 'moved-sideways')... and then moved it back to 0.  This is a simple way to set a mesh pivot point.  Now, we just do simple rotate on the moon, and it spins... on its offset pivot point... with its position (+offset) being continuously set == planet.

But there is challenge ahead.  Ideally, the moon should spin independently, too.  More fun to come, eh?

##### Share on other sites

Thanks Wingnut! I read about the bakeTransform thing but wasn't sure where it would actually be useful, now I get it!

I had thought that maybe moving its center reference somehow might work but as you say, then it won't be able to spin on its own axis.

What we need is a method to move a mesh about an axis at an arbitrary point in space, away from its own axes. But I'm not sure how to maintain orbital momentum in that case either.

Bonus points: it can work in 3 dimensions too...

##### Share on other sites

@Wingnut - I wasn't aware that you could bake a center offset in Babylon.js - as this is an incredibly valuable function. If you don't add this to the Spaces, Parent, Pivot post on the BJS forum page, I'll need to do it, as I doubt many users are aware this exists and just how valuable this is. I need to begin assembling some of the more valuable posts and methods for parenting and center calculations and functions, and begin adding this to the docs - as was my intention last year, but never seem to have the time.

Add just to burst your bubbles a bit, the earth rotates counterclockwise around the sun and on its axis which is offset 23.4 degrees. The moon rotates counterclockwise also - which is observed in your Playground scene. Details, details.

DB

##### Share on other sites

Hi again, jb!  And db!

JB, do you want this solar system to be... um... accurate?  Are you trying for a reasonably-precise modeling of our solar system, or creating a general solar system to shoot down enemy fighters within?

If you are seeking OUR solar system... and seeking accuracy, then you have one more variable that will be a pain.  Axial tilt (as mentioned by DB before I could SEND this post)    https://en.wikipedia.org/wiki/Moon#/media/File:Earth-Moon.PNG

If that isn't tumor-causing enough, here's the list of moons per planet... http://www.windows2universe.org/our_solar_system/moons_table.html

Let's pretend that you, JB, invented a new JS object called "smart moon".  Maybe it starts as a basic BabylonJS mesh, but then you add more power to it.  You add property values and methods/functions... until this smart moon... can be "autonomous".  Automatic.  When everything is coded just right, you might do:

var myMoon = new smartMoon("Luna", "Earth", size, material, orbitalCycle, axialTilt, rotationSpeed, retroGradeAltitude, proGradeAltitude, ellipticalRotation, etc, whatever, etc);

Now you have a "moon factory".  You told it which planet to orbit ("earth") and numerous other things, including orbital elements.  The actual moon mesh is created INSIDE of YOUR smartMoon code.  If you had such a func/system as smartMoon()... the remainder of your task seems a bit easier, eh?  SmartMoon() [actually the smartMoon's updateMyself func] ... handles all the dirty work.  All you have to do is create 181 of them.

Code that lives ON a mesh, can have the power to control that mesh.  You add a brain to the mesh.  It becomes orbitally-intelligent.  A robot.

Fire'n'forget... a smartMoon-class object has everything it needs to do its own orbiting, via having a function called updateMyself().  Inside the main program render loop (scene.beforeRender)... perhaps use... game.orbitals.forEach(function() { updateMyself() }).

Easy as pie.  Piece of cake.  SmartMoons!  Yay!  If you are really good, the same smartMoon() could be used to make the 8 planets, too, and set their target to "sun".  Just some thoughts.  Probably not wise thoughts.  Good luck, JB.  Stay in touch.

Hi @dbawel!  Yeah, the first time I saw Deltakosh do a bake to set a pivot point, I about crapped a rhino.  I think I would have preferred mesh.bake("position/rotation/scale", new BABYLON.Vector3(x, y, z))... but whatever gets the job done.    You are right... very valuable activity.  Needing three steps to do it?  Unfortunate.  I hear there are other ways to do it...  transformCoordinates, I guess... possibly with a matrix involved.  That stuff scares my dog.

Add yes, poor details on my part.  I hadn't finished my first cup of morning coffee, yet.

##### Share on other sites

Not exactly accurate no, in fact I mainly just wanted to understand how to make things rotate in relation to eachother (rather than the center). I do have a space based game in mind but close accuracy won't be a factor. I *did* want to make orbits accurate for the mass and distance from the object (so geosynchronous and not) but not even simulating our solar system exactly - to be honest that would be pretty dull in realtime right?

I wasn't going to consider axial tilt but it sounds like baking a transformation would solve that?

Your smartMoon class/prototype would be a nice way to do it, in fact it wouldn't just apply to any moon but should be any orbiting object in the system. That's probably a ways off, and unfortunately still doesn't solve the problem of how to do orbits around an arbitrary axis!

So maybe it can be done with a series of translates which offset the translation of the parent and then apply their own. Or just do it more by hand. I haven't done matrices for a long time and not in 3d, but I have a feeling this is possible, I just don't know how. Apparently the OrbitalCamera has some .alpha and .beta rotational vectors?

##### Share on other sites

Hi again, jb.  http://www.babylonjs-playground.com/#1UGDQC#7

Here, I use no baking... but I still do two different orbits at arbitrary angles and positions.

Moon - position set by line 40.  Then, in line 50, I put a formula-value in the Y position  [Math.sin(alpha)/15].  Easy, eh?  How do you like that vector3 class .addInPlace method?  Sweet and easy, eh?  moon.position is a vector3, so we get to use all the cool tools on the vector3 class.  It has a crapload of 'em.    addInPlace is one of the best.

Planet - position is set by sun (via line 11 and line 29).  Orbit angle is set by using a slight z-rot in line 16 (more about that below).  This method is not quite as "arbitrary", because it is still using planet.parent.y in line 45.  But where IS the parent?  Where is the sun?  Are we in a total eclipse?    In lines 12-16, I made it invisible, removed its now-not-needed material, and gave it a splash of z-rotation (mentioned earlier).  We made the sun be an invisible "gizmo" in space, and it would be wiser to make it a box or plane, now... less vertices than sphere.  So, orbiting invisible gizmos in space... is an option, too.

Matrix transformations have been known to scare household pets, so use those only as a last resort.    (just kidding, of course)  Framework authors really tried to make BJS as easy as possible, and it is, if we allow it to be so.  Yet, it is also easy to lift the hood of BJS, and rewire parts of it, or the whole darned thing, if wanted.  I love it.  It's a webGL experimenter's dream come true, really.

I actually got mentally overwhelmed when I tried to think-up all the possibilities for BJS.  One of the greatest possibility wideners of all... is having its author(s) be SO NEARBY and SO willing to make modifications or teach you WHY a certain modification is wise/not... AND to offer alternative ways.  For me, that aspect was and is... HIGHLY valuable, and I'm starting to learn how to offer alternatives to others.  (NOT alternative frameworks.  BJS rocks solid... no reason to wander.  I'm speaking-of alternative methods of getting something coded-up/visualized, of course)

The more alternatives you have in your personal BJS/webGL toolbox, the better EVERYTHING rolls along... helping others, making tests, having your own fun.  Deltakosh is a superman, he really is.  He has answered some 21 trillion questions, now... (7 trillion were repeats,18 trillion were not on the topic of BJS at all), and he has kept a wonderful attitude and spirit through it all.  And his code is frogs-ass water-tight.  Not only is BJS a great framework and invention, but it has a great core team, and that is...  umm... marvelous.  That's the best word to describe my experiences with BJS and its programmers/fans.  Marvelous.  Party on, stay in touch,

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.