Reputation: 101
I'm very new to programming and I've gotten a school assignment for which I have to create a simulation of the earths orbit around the sun in p5.js . We were offered a simplified way to compute the gravitational pull but I wanted to use the actual formula (Fg = GMm/r^2). In my code, one pixel equals 10^9 meters or a million km. If I use the actual masses of both the sun and the earth, as well as the actual distance between them, I have to put the speed at which the earth travels at around 1 pixel per second or a million km/s, which is around 30,000 times the actual speed of the earth in orbit. My code:
x = 550;
y = 400;
vy = -1;
vx = 0;
dt = 1;
sunSize = 80;
planetSize = 10;
// 1 pixel equals 1 million km
canvasSize = 800;
starAmount = 600;
function setup() {
frameRate(60);
noStroke()
solarXY = 0.5 * canvasSize;
xSun = solarXY;
ySun = solarXY;
createCanvas(canvasSize, canvasSize);
M = 1.989 * pow(10, 30);
m = 5.972 * pow(10, 24);
background(0);
for (i = 0; i < starAmount; i++) {
starX = Math.random() * canvasSize;
starY = Math.random() * canvasSize;
starSize = Math.random() * 3 + 1
ellipse(starX, starY, starSize, starSize);
}
fill(255, 192, 0);
ellipse(xSun, ySun, sunSize, sunSize);
}
function draw() {
r = sqrt(sq(xSun - x) + sq(ySun - y)) * pow(10, 9);
Fg = 6.67 * pow(10, -11) * m * M / sq(r);
if (x >= xSun) {
angle = atan((ySun - y) / (x - xSun));
} else {
angle = PI + atan((ySun - y) / (x - xSun));
}
xOld = x;
yOld = y;
Fgx = cos(angle) * Fg
Fgy = sin(angle) * Fg
ay = Fgy / m;
ax = -Fgx / m;
vy += ay * dt;
vx += ax * dt;
y += vy * dt;
x += vx * dt;
fill(30);
ellipse(xOld, yOld, planetSize, planetSize);
fill(0, 0, 192);
ellipse(x, y, planetSize, planetSize);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
Do you know what the cause could be? Thanks in advance.
Upvotes: 9
Views: 299
Reputation: 99144
You appear to have acceleration in meters per second 2, and velocity in pixels per second. Then you combine them:
vy += ay * dt;
vx += ax * dt;
Your gravitational accelerations are a billion times too strong. So your planet must move about 31,623 times faster than normal to keep a circular orbit.
Upvotes: 6