Skip to content

Instantly share code, notes, and snippets.

@jkwok91
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkwok91/0c3eb1b87c61840d2ffb to your computer and use it in GitHub Desktop.
Save jkwok91/0c3eb1b87c61840d2ffb to your computer and use it in GitHub Desktop.
misha's cannon
class Cannonball {
float rad;
color myColor;
PVector loc; // location
PVector v; // velocity
PVector a; // acceleration
float mass;
Cannonball(float r, float x, float y, float angle) {
rad = r;
mass = r*10;
myColor = getColor(random(0, 255));
loc = new PVector(x, y);
v = new PVector(7.5*cos(angle),7.5*sin(angle)); // initial v
a = gravity; // always
}
void update() {
v.add(a);
loc.add(v);
bounce();
a = gravity; //reset acceleration
}
void applyForce(PVector force) {
PVector f = PVector.div(force, mass);
a.add(f); //net forces
}
void bounce() {
if (loc.x > width-rad/2) {
v.x *= -1; //reverse x motion
loc.x = width-rad/2; //constraint
}
else if (loc.x < rad/2) {
v.x *= -1; //reverse x motion
loc.x = rad/2;
}
if (loc.y > height-rad/2) {
v.y *= -1; //reverse y motion
loc.y = height-rad/2;
}
else if (loc.y < rad/2) {
v.y *= -1; //reverse y motion
loc.y = rad/2;
}
}
void display() {
stroke(myColor);
fill(myColor);
ellipse(loc.x, loc.y, rad, rad);
}
String toString() {
return "velocity: <"+v.x+","+v.y+"> accel: <"+a.x+","+a.y+"> and it is at <"+loc.x+","+loc.y+">.";
}
}
/*
misha's cannon
*/
int w = 600;
int h = 300;
float angle;
float G = 0.0981; // gravitational constant
PVector gravity;
float rad; // radius of cannonballs
ArrayList<Cannonball> launched;
void setup() {
size(w, h);
background(0);
angle = PI/2;
gravity = new PVector(0, G);
rad = 20; //radius of cannonball
launched = new ArrayList<Cannonball>();
}
void draw() {
background(0);
angle = atan(((height-rad)-mouseY)/(mouseX-rad));
angle = constrain(angle,0,PI/2);
stroke(255);
fill(255);
text("click me",width/2,height/2);
text("angle: "+degrees(angle),rad,height-rad);
line(0, height, 75*cos(angle), height-(75*sin(angle)));
for (Cannonball cb : launched) {
cb.update();
cb.display();
}
}
void newCB() {
Cannonball cb = new Cannonball(rad, 0, height, angle);
launched.add(cb);
}
void mousePressed() {
newCB();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment