I am building 3D solar system containing (sun > earth > moon).
I have difficult to add the part which the moon rotate around earth.
I separated between "moon" and other stars.
The problem is that the center of earth is not const like the sun.
I know that earth is in starsList[1] so I thought to translate the moon to this place but got weird result..
Someone have an idea how to do this?

mat4.translate(mvMatrix, [0, 0, z]);

for (i = 0; i < starsList.length; i++) { 

    if (starsList[i].name == "moon"){
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[1].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]); 
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);
        mat4.translate(mvMatrix, starsList[i].initPlace);
        mat4.rotate(mvMatrix, degToRad(starsList[i].angle), [0, 1, 0]);

I assume, that you are using 3D/2D models for the sun and the planets and the moon. In this case, you can pass uniforms for each planet to the vertexShader which contain data about the position of an object.

For example the sun will always have a steady position in the middle of the screen. And the earth will move relative to the sun and the moon relative to the earth.

First you create uniforms for your shaders:

uniform vec4 sunPos;
uniform vec4 earthPos;
uniform vec4 moonPos;

Then you get their location so you can change them:

GLint sunPos = glGetUniformLocation(shaderPrg, "sunPos");
GLint earthPos = glGetUniformLocation(shaderPrg, "earthPos");
GLint moonPos = glGetUniformLocation(shaderPrg, "moonPos");

Then you set the sunPos to vec4(0, 0, 0, 1)

glUniform4i(sunPos, 0, 0, 0, 1);

Then you calculate the Earth's position according to the sun for each frame in your gameloop:

glUniform4f(earthPos, calcEarthX(), calcEarthY(), calcEarthZ(), 1.0f);

Note that the calc function need to return a float or a GLfloat

Then you just do the same for the Moon's postion for each frame.

glUniform4f(moonPos, calcMoonX(), calcMoonY(), calcMoonZ(), 1.0f);

Now you can use these uniforms in your shaders render each model correctly.

There is surely an easier solution, but I am new to openGL, too. ;D


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .