-
Notifications
You must be signed in to change notification settings - Fork 5
/
Particle.pde
86 lines (67 loc) · 1.95 KB
/
Particle.pde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// The Nature of Code
// <http://www.shiffman.net/teaching/nature>
// Spring 2010
// PBox2D example
// A circular particle
class Particle {
// We need to keep track of a Body and a radius
Body body;
float r;
Particle(float x, float y, float r_) {
r = r_;
// This function puts the particle in the Box2d world
makeBody(x,y,r);
}
// This function removes the particle from the box2d world
void killBody() {
box2d.destroyBody(body);
}
// Is the particle ready for deletion?
boolean done() {
// Let's find the screen position of the particle
Vec2 pos = box2d.getScreenPos(body);
// Is it off the bottom of the screen?
if (pos.y > height+r*2) {
killBody();
return true;
}
return false;
}
//
void display() {
// We look at each body and get its screen position
Vec2 pos = box2d.getScreenPos(body);
// Get its angle of rotation
float a = body.getAngle();
pushMatrix();
translate(pos.x,pos.y);
rotate(-a);
fill(255,50,10,50);
noStroke();
strokeWeight(1);
ellipse(0,0,r*2,r*2*((height-pos.y)/100));
// Let's add a line so we can see the rotation
line(0,0,r,0);
popMatrix();
}
// Here's our function that adds the particle to the Box2D world
void makeBody(float x, float y, float r) {
// Define a body
BodyDef bd = new BodyDef();
// Set its position
bd.position = box2d.screenToWorld(x,y);
body = box2d.world.createBody(bd);
// Make the body's shape a circle
CircleDef cd = new CircleDef();
cd.radius = box2d.scaleScreenToWorld(r);
cd.density = 1.0f;
cd.friction = 0.01f;
cd.restitution = 0.3f; // Restitution is bounciness
body.createShape(cd);
// Always do this at the end
body.setMassFromShapes();
// Give it a random initial velocity (and angular velocity)
body.setLinearVelocity(new Vec2(random(-10f,10f),random(5f,10f)));
body.setAngularVelocity(random(-10,10));
}
}