2

So I'm building a little gravity simulation just for fun in JSFiddle. Here is my script so far:

var elements = [
    {
        "id": "earth",
        "mass": 30,
        "left": 30,
        "top": 30,
        "hSpeed": 300,
        "vSpeed": -300
    }, {
        "id": "sun",
        "mass": 5000,
        "left": 50,
        "top": 50,
        "hSpeed": 0,
        "vSpeed": 0
    }];

var intervalTime = 10;

var intervalID;

var getDistance = function(x1, y1, x2, y2) {

    // h^2 = x^2 + y^2

    var xD = x1 - x2;
    var yD = y1 - y2;
    var hSq = xD * xD + yD * yD;

    return Math.sqrt(hSq);
};

var getXPortion = function(val, x1, y1, x2, y2) {

    var hD = getDistance(x1, y1, x2, y2);
    var xD = x2 - x1;

    if ((hD == 0) || (xD == 0) || (val == 0)) {
        return 0;
    }

    return val / hD * xD;
};

var getYPortion = function(val, x1, y1, x2, y2) {

    var hD = getDistance(x1, y1, x2, y2);
    var yD = y2 - y1;

    if ((hD == 0) || (yD == 0) || (val == 0)) {
        return 0;
    }

    return val / hD * yD;
};

var animateWorld = function() {

    // Calculate the change in speed for each element
    // based on the gravity of all the other elements
    var i = 0;
    var j = 0;
    var dist = 0;
    var mass = 0;
    var grav = 0;
    var change = 0;
    var chX = 0;
    var chY = 0;
    for (i in elements) {
        for (j in elements) {
            if (i != j) {
                dist = getDistance(
                    elements[i].left,
                    elements[i].top,
                    elements[j].left,
                    elements[j].top
                );
                mass = elements[i].mass * elements[j].mass;
                grav = dist == 0 ? 0 : mass / (dist * dist);
                change = grav / elements[i].mass;
                elements[i].hSpeed += getXPortion(
                    change,
                    elements[i].left,
                    elements[i].top,
                    elements[j].left,
                    elements[j].top
                );
                elements[i].vSpeed += getYPortion(
                    change,
                    elements[i].left,
                    elements[i].top,
                    elements[j].left,
                    elements[j].top
                );
            }
        }
    }

    // Calculate the new position for each element
    // based on the speed and move each element to it's new position
    for (i in elements) {
        elements[i].left += elements[i].hSpeed / 1000;
        elements[i].top += elements[i].vSpeed / 1000;
        $('#' + elements[i].id).css('left', elements[i].left + '%');
        $('#' + elements[i].id).css('top', elements[i].top + '%');
    }

};

$(document).ready(function() {
    intervalID = window.setInterval(animateWorld, intervalTime);
});

I am allowing all the objects to act upon each other based on their respective mass and distance. The issue is that all the objects are drifting slowly to the right. As this is a closed system, I would expect one to move to the right only if another moves equally to the left based on mass, so it should be impossible for them all to drift in the same direction over time. I think one of the following is happening, but I'm not sure which:

  1. The floating points used in the math are causing minor rounding issues that cause this (Unlikely)
  2. The fact that I first calculate the effect of each body on the other and then move them is causing some bias. I this is the case, how should I fix it?

Any ideas? Is there an easier way to do this?

4
  • At a first look, it looks like the sun only drifts right, but not left, maybe that'll help the debugging process
    – Kevin L
    Jul 14, 2014 at 16:04
  • 1
    Your earth seems to have quite a large effect on your sun. Change the position of the earth to the top right corner at the start and change the speeds to fire it towards bottom left so that it runs in reverse and the sun starts moving the other way
    – AeroX
    Jul 14, 2014 at 16:24
  • @AeroX. I'm not trying to build a realistic scale, just a realistic simulation of the gravity effects regardless the underlying assumptions
    – neelsg
    Jul 14, 2014 at 16:29
  • @neelsg I have no understanding of the physics but just noticed I was able to get the sun to drift in the opposite direction by changing the starting parameters. Didn't know if it would give you somewhere else to start debugging
    – AeroX
    Jul 14, 2014 at 16:31

3 Answers 3

2

I think it's your #2 possibility.

You should avoid looping through your objects and applying forces one at a time. This would mean that the simulation would behave differently depending on the order of the objects in your array, which shouldn't happen.

I would recommend adding a few more fields to each objects, including an 'hAcceleration' and 'vAcceleration'. Loop through all the objects and compute the acceleration from gravity for each.

THEN, loop through all your objects, adding acceleration onto velocity. Then, loop once more, adding velocity to position. This is how I've done it in the past, and it's seemed to work well.

1
  • It's actually not only this. I followed your suggestion and only updated the speeds after calculating them for all objects. The drift is slower, but still there JSFiddle
    – neelsg
    Jul 14, 2014 at 16:18
2

Actually one problem was what @kbelder said, but another was a physics oversight on my part as fixed in JSFiddle. The problem is that I gave the one object (earth) a speed (i.e momentum) and the other (sun) no compensating momentum, so the group of as a whole had a small momentum. Note the "hSpeed": -1.8 and "vSpeed": 1.8 values for "sun" to compensate.

var elements = [
    {
        "id": "earth",
        "mass": 30.0,
        "left": 30.0,
        "top": 30.0,
        "hSpeed": 300.0,
        "vSpeed": -300.0
    }, {
        "id": "sun",
        "mass": 5000.0,
        "left": 50.0,
        "top": 50.0,
        "hSpeed": -1.8,
        "vSpeed": 1.8
    }];
0

You are using integer types. Dividing integers has to be done on the very last step. Each division you do causes a small lost of info because the result has to be casted to integer. Try to make all your operations on double types instead of integer and cast only when you set the new positions to your elements. Any other calculation has to stay in double.

Multiplying one operand with 1.0 (i.e. to cast it to double) will help a little by the way. So you can do something like:

return val * 1.0 / hD * xD;

Which returns uncasted unrounded double.

3
  • That's not it. I modified it per your suggestion and it still drifts JSFiddle
    – neelsg
    Jul 14, 2014 at 16:10
  • I didn't mean only this line. You have to keep all your data in double, set the new position, and compute the next one based on the double data and not on the new integer positions.
    – AHH
    Jul 14, 2014 at 16:12
  • Thanks for the feedback, but if you look at the fiddle, you'll see that I did it for every relevant line
    – neelsg
    Jul 14, 2014 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.