Search code examples
javascriptmathastronomy

Trying to write some maths from Wikipedia in Javascript (sun position computation)


I am trying to approximate the position of the sun in XYZ for a threejs project.

I am following the maths found here: http://en.wikipedia.org/wiki/Position_of_the_Sun

Following the above, I have written the following Javascript code:

    var n = ((2440587.5 + (this.datemillis / 8.64E7)) - 2451545);
    var L = 280.460 + 0.9856474 * n;
    var g = 357.528 + 0.9856003 * n;
    L = (L + 360) % 360;
    g = (g + 360) % 60;
    var lambda = L + 1.915 * Math.sin(g) + 0.0020 * Math.sin(2 * g);
    var r = 1.00014 - 0.01671 * Math.cos(g) - 0.00014 * Math.cos(2 * g);
    var e = 23.439 - 0.0000004 * n;

    var x = (r * this.constants.EARTH_RADIUS * 2) * Math.cos(lambda);
    var y = (r * this.constants.EARTH_RADIUS * 2) * Math.cos(e) * Math.sin(lambda);
    var z = (r * this.constants.EARTH_RADIUS * 2) * Math.sin(e) * Math.sin(lambda);

this.datemillis is returned by the getMillisecond function of the Javascript date object. It is updated each frame so that time advances at about 1 hour every 2 seconds.

However something must not be correct as this does not produce the expected result. When I apply the computed x y z coordinates to my sun in my threejs project, I can see the sun rotate around the earth (sitting in 0,0,0) but at a very slow rate (rotating the earth in a few days instead of 24 hours).

I'm thinking it might have something to do with the angle calculations that I'm not doing correctly (degrees/radians?) but I'm not very good at maths so I don't really know what I'm doing so maybe I just misinterpreted the Wiki calculations.

If somebody could spot something obvious I'm doing wrong and help me fix this, would be greatly appreciated!

Thanks

EDIT: so my sun currently is not rotating around the earth in a continous way - it rotates clockwise/counterclockwise alternatively and sometimes jumps positions...


Solution

  • I cannot answer your question but I do know this is a solved problem in threejs. There is an example running in an architecture/engineering workflow on Github on this topic. The sun position code is here https://github.com/radio412/viewer/blob/gh-pages/sun-position.js

    You can see it being tapped for a directional light in threejs at line 108 here: https://github.com/radio412/viewer/blob/gh-pages/va3c-viewer.js