Implementing gravity help!
in
Programming Questions
•
1 year ago
So I've got classes Rect, MotileRect, and GravRect. Rect is an on-screen rectangle, MotileRect can move, and GravRect is *supposed* to pull MotileRects in toward it. Here they are:
The problem is that my current implementation of gravity... doesn't work. It flings the rect it's supposed to be sucking in ALL OVER THE PLACE, in a way that's not consistent with anyone's laws of gravity, except maybe the LHC people. Anyway, what code should I use to make the gravity work?
- class Rectangle {
PVector pos;
int h;
int w;
int r;
int g;
int b;
Rectangle (PVector inpos, int inw, int inh, int inr, int ing, int inb) { //define with a vector
pos = inpos;
h = inh;
w = inw;
r = inr;
g = ing;
b = inb;
}
void render () {
fill(r, g, b);
noStroke();
rect(pos.x, pos.y, w, h);
}
float getCX() { //get center-x
return pos.x-(w/2);
}
float getCY() { //get center-y
return pos.y-(h/2);
}
}
class MotileRect extends Rectangle {
PVector speed; //in pixels per 1/10th second.
Trigger timer;
MotileRect(PVector inpos, int inw, int inh, int inr, int ing, int inb, PVector inspd) {
super(inpos, inw, inh, inr, ing, inb);
speed = inspd;
timer = new Trigger(10);
}
void update() {
while (timer.fires ()) {
pos.add(speed);
}
}
}
class GravRect extends Rectangle {
float magnitude;
GravRect (PVector inpos, int inw, int inh, int inr, int ing, int inb, float inmag) {
super(inpos,inw,inh,inr,ing,inb);
magnitude = inmag;
}
void affect(MotileRect target) {
PVector effect = new PVector( magnitude/(pos.x-target.pos.x), magnitude/(pos.y-target.pos.y));
target.speed.add(effect);
}
}
The problem is that my current implementation of gravity... doesn't work. It flings the rect it's supposed to be sucking in ALL OVER THE PLACE, in a way that's not consistent with anyone's laws of gravity, except maybe the LHC people. Anyway, what code should I use to make the gravity work?
1