-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphysics.pde
More file actions
65 lines (57 loc) · 2.17 KB
/
physics.pde
File metadata and controls
65 lines (57 loc) · 2.17 KB
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
void initPhysics()
{
physics=new VerletPhysics2D();
// set screen bounds as bounds for physics sim
physics.setWorldBounds(new Rect(0,0,width,height));
// add gravity along positive Y axis
physics.addBehavior(new GravityBehavior2D(new Vec2D(0,0.1)));
// compute spacing for string particles
float delta=(float)width/(string_res-1);
for(int i=0;i<string_res;i++)
{
// create particles along X axis
VerletParticle2D p=new VerletParticle2D(i*delta,height/2);
physics.addParticle(p);
// define a repulsion field around each particle
// this is used to push the ball away
physics.addBehavior(new AttractionBehavior2D(p,delta*1.5,-20));
// connect each particle to its previous neighbour
if(i>0)
{
VerletParticle2D q=physics.particles.get(i-1);
VerletSpring2D s=new VerletSpring2D(p,q,delta*0.5,0.1);
physics.addSpring(s);
}
}
// lock 1st & last particles
physics.particles.get(0).lock();
physics.particles.get(physics.particles.size()-1).lock();
// create ball
// first create a particle as the ball centre
VerletParticle2D c=new VerletParticle2D(width/2,100);
physics.addParticle(c);
// list to store all ball perimeter particles
List<VerletParticle2D> cparts=new ArrayList<VerletParticle2D>();
for(int i=0;i<ball_res;i++)
{
// create a rotation vector, scale it to the radius and move relative to ball center
Vec2D pos=Vec2D.fromTheta(i*TWO_PI/ball_res).scaleSelf(ball_radius).addSelf(c);
// create particle and add to lists
VerletParticle2D p=new VerletParticle2D(pos);
cparts.add(p);
physics.addParticle(p);
// connect to ball center for extra stability
VerletSpring2D sp=new VerletSpring2D(c,p,ball_radius,0.01);
physics.addSpring(sp);
// also connect all perimeter particles sequentially
if(i>0)
{
VerletParticle2D q=cparts.get(i-1);
physics.addSpring(new VerletSpring2D(p,q,p.distanceTo(q),1));
}
}
// finally close ball perimeter by connecting first & last particle
VerletParticle2D p=cparts.get(0);
VerletParticle2D q=cparts.get(ball_res-1);
physics.addSpring(new VerletSpring2D(p,q,p.distanceTo(q),1));
}