Skip to content

Instantly share code, notes, and snippets.

@alexalemi
Created November 16, 2011 21:54
Show Gist options
  • Save alexalemi/1371569 to your computer and use it in GitHub Desktop.
Save alexalemi/1371569 to your computer and use it in GitHub Desktop.
GravitySim
//Make the rocket object
Rocket myRocket;
//Define planets arraylist
planets = new ArrayList();
// Global variables
//Strength of gravity
float gravstrength = -0.01;
// Thrust strength
float dv = 0.06;
//Image size
int imagesize = 200;
void setup() {
size(600,600);
frameRate(70);
smooth();
// Parameters go inside the parentheses when the object is constructed.
myRocket = new Rocket(color(255,0,0),100,100,0.1,0.1);
}
void draw() {
background(220);
myRocket.drive();
gravity();
myRocket.display();
if (keyPressed) {
myRocket.thrust(key)
}
if (mousePressed && (mouseButton == LEFT)) {
planets.add(new Planet(mouseX,mouseY));
}
else if (mousePressed && (mouseButton == RIGHT)) {
for (int i=0; i<planets.size(); i++) {
planet = planets.get(i);
if (dist(mouseX,mouseY,planet.pos.x,planet.pos.y) < 20) {
planets.remove(i);
}
}
}
drawplanets();
}
// Rocket has a x,y vx,vy and color
class Rocket {
color c;
float x;
float y;
float vx;
float vy;
// The Constructor is defined with arguments.
Rocket(color tc, float tx, float ty, float tvx, float tvy) {
c = tc;
x = tx;
y = ty;
vx = tvx;
vy = tvy;
}
void display() {
//Draw the rocket
stroke(0);
fill(c);
rectMode(CENTER);
ellipse(x,y,10,10);
}
void thrust(string key) {
//Apply thrust
fill(color(255,125,0));
if (key=='w') {
vy -= dv;
triangle(x-2,y+5,x+2,y+5,x,y+10);
//rect(x,y+5,5,10);
} else if (key=='s') {
vy += dv;
triangle(x-2,y-5,x+2,y-5,x,y-10);
} else if (key=='a') {
vx -= dv;
triangle(x+5,y-2,x+5,y+2,x+10,y);
} else if (key=='d') {
vx += dv;
triangle(x-5,y-2,x-5,y+2,x-10,y);
}
}
void drive() {
//Euler step update
x += vx;
y += vy;
if (x > width || x < 0) {
vx = -vx;
}
if (y > height || y < 0) {
vy = -vy;
}
}
}
void drawplanets() {
fill(color(0,0,255,10));
for (int i=0; i< planets.size(); i++) {
planet = planets.get(i);
ellipse(planet.pos.x,planet.pos.y,10,10);
}
}
void gravity() {
PVector totforce = new PVector(0,0);
for (int i=0; i < planets.size(); i++) {
totforce.add(planets.get(i).force())
}
totforce.mult(gravstrength);
myRocket.vx += totforce.x;
myRocket.vy += totforce.y;
}
class Planet {
PVector pos;
Planet(float tx, float ty) {
pos = new PVector(tx,ty);
}
PVector force() {
PVector r = new PVector(myRocket.x,myRocket.y);
r.sub(pos);
float ir32 = pow(r.mag(),-3./2);
r.mult(ir32);
return r;
}
float pot(int i, int j) {
float x = width/imgsize * i;
float y = height/imgsize * j;
float pot = gravstrength / dist(x,y,pos.x,pos.y);
return pot;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment