Gravity in a solar system

I’m trying to simulate a solar system type thing where on planet orbits around a sun. The planet has an initial velocity of x+2. However, it always seems to follow this long elliptical orbit.

I’m trying to get it so that after a while, it’s orbit soon smooths out into more of a round circle orbit, but I can’t figure out how.

PVector pos = new PVector(100, 100);
PVector dir = new PVector(2, 0);

void setup()
{
  size(600, 600);
}

void draw()
{
  background(255);
  
  fill(0);
  ellipse(300, 300, 50, 50);
  
  noFill();
  stroke(2);
  ellipse(pos.x, pos.y, 40, 40);
  
  PVector grav = new PVector(300 - pos.x, 300 - pos.y);
  grav.normalize();
  grav.div(dist(300, 300, pos.x, pos.y) / 15);
  
  dir.add(grav);
  pos.add(dir);
}

So right now, it follows a highly elliptical orbit, and orbits like that forever, but I want it to eventually go to a circle orbit. Any ideas?

Hello,

I can share this most excellent resource:
https://natureofcode.com/book/

:)

I suspect that orbits of astronomical objects become more circular over time due to gravitational interactions with objects other than the one they’re orbiting. So why not try to put one more in the system to see what happens?

I mean something like this.

2 Likes

if you spawn the orbiting body at 300, 100 instead it will be more circular, and change the dir to 3, 0 instead

@Cybernet,

With a bit of math you can plug in some “exact” values for your PVector dir (velocity) to give you a circular orbit:

image

Give it some thought.

I won’t give you the answer… the best part of this for me was solving this from an understanding of the fundamentals.

Circular orbits first… elliptical orbits later.

:)

Additional references:

1 Like