#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# Question about gravitational attraction in processing

edited May 2016

Hey, so I'm doing an assignment of a space game. I'm having a bit of trouble with the gravitational attraction aspect of it, presumably because it only occurs if certain conditions are met.

What I'm trying to do is have the gravitational pull of a planet affect the asteroids (Hostiles) ONLY during the time the planet is passing by the screen. However, when the planets do come onto the screen, some nearby hostiles keep moving as if the planet doesn't exist, and the ones trailing behind the planet freeze and begin to rapidly move up and down (unintended) when the planet is close to exiting the screen.

Here's my code for it (I'll just include the code of the entire class, as it might help to put it into a complete context).

`````` class Hostile {
PVector loc;
PVector velo;
int hitCounter = 0;
int stability = 3;
float r;
PVector accel;

Hostile(PVector _loc, PVector _velo) {

loc = new PVector(_loc.x, _loc.y);
velo = new PVector(_velo.x, _velo.y);
accel = new PVector(0, 0);
}

void display() {
ellipse(loc.x, loc.y, 50, 50);
}

void update() {
loc.sub(velo);

for (int i = 0; i < missiles; i++ ) {
if (dist(missile[i].loc.x, missile[i].loc.y, loc.x, loc.y) <= 30 ) {
loc.x = random(2500, 4000);
loc.y = random(50, 550);
hit = true;
}
}
//
//for ( int i = 0; i < 1; i++ ) {
if ( dist(planet[0].loc.x, planet[0].loc.y, loc.x, loc.y ) <= 1000 && planet[0].loc.x < 1000 && planet[0].loc.x > 200 ) {
println("planet in range " + planet[0].loc.x);
r = dist(loc.x, loc.y, planet[0].loc.x, planet[0].loc.y);
if ( r < 200 ) {
r = 200;
}

//println(i);

//velo.y = 3;
//velo.x = 10;
accel.x = (planet[0].loc.x - loc.x)*15000/pow(r, 3);
accel.y = (planet[0].loc.y - loc.y)*15000/pow(r, 3);

}

if ( planet[0].loc.x < 199 ) {
loc.y = random(50, 550);
velo.x = 5;
velo.y = 0;
accel.x = 0;
accel.y = 0;
}
//} //NEEDS TO BE FIXED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
``````
Tagged: