Create a gist now

Instantly share code, notes, and snippets.

Colliding galaxies in Processing
// Galaxy collisions
Star[] Stars;
PVector[] galp;
PVector[] galv;
color[] galcol, galcol2;
boolean paused = false;
int side = 100; // border around Stars' initial positions
int Startot = 300; // number of Stars
int obsize = 10; // size of Stars
int obshape = 2; // shape (1 = point, 2 = ellipse)
float speed = 8; // intial speed limit
float gravity = 0.1; // gravity strength coefficient
float gpower = 2.0; // gravity power variable (range 1 - 2.5)
float galrad = 70; // galaxy radius
float sep = 150; // galaxy seperation
float gv = 0.8; // galaxy vertical velocity
void setup()
{
translate(width/2, height/2);
frameRate(25);
size(800, 600);
background(0);
galp = new PVector[2];
smooth();
galp[0] = new PVector(-sep,0);
galp[1] = new PVector(sep,0);
galv = new PVector[2];
galv[0] = new PVector(0,gv);
galv[1] = new PVector(0,-gv);
int trans = 5;
galcol = new color[2];
galcol2 = new color[2];
galcol[0] = color(100,100,255,trans);
galcol[1] = color(200,200,0,trans);
galcol2[0] = color(50,50,255);
galcol2[1] = color(200,200,0);
Stars = new Star[Startot];
strokeWeight(1);
for (int i=0; i<Stars.length; i++) Stars[i] = new Star();
}
void draw()
{
println(frameCount/25);
background(0);
translate(width/2, height/2);
noStroke();
for (Star o:Stars) o.gravity();
for (Star o:Stars)
{
if(paused==false) o.move();
fill(o.col);
noStroke();
ellipse(o.p.x, o.p.y, obsize, obsize);
stroke(o.col2);
point(o.p.x, o.p.y);
}
}
class Star
{
int id;
PVector p, v;
float mass;
color col, col2;
int gal;
Star()
{
gal = int(random(0., 2.));
float rad = random(0, galrad);
float ang = random(0., 360.);
PVector gp = new PVector(cos(radians(ang))*rad, sin(radians(ang))*rad);
p = new PVector(gp.x, gp.y);
p.add(galp[gal]);
float d = 0.008;
v = new PVector(gp.y * d , gp.x * -d);
v.mult(speed);
v.add(galv[gal]);
col = galcol[gal];
col2 = galcol2[gal];
}
void gravity()
{
for (Star o:Stars)
{
if (o!=this)
{
PVector d = new PVector(p.x, p.y);
d.sub(o.p);
float power = constrain(d.mag(), 1, 10000);// prevent infinite gravity
power = pow(power, -gpower); // inverse power function
d.mult(power*-gravity);
v.add(d);
}
}
}
void move()
{
p.add(v);
}
}
void keyPressed()
{
if (key=='p') paused = !paused;
}
@geotheory
Owner

Video of a toy gravity model I've written in Processing, demonstrating the collision of 2 galaxies. The code simulates a basic inverse distance square gravity model.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment