2022-05-03
铺垫:加速度、速度、行程的关系基本的原理,在这个例子里展示完整。
- Shiffman, Daniel. Learning Processing: a beginner's guide to programming images, animation, and interaction. Morgan Kaufmann, 2009. P89
float x = 100; // x location of square
float y = 0; // y location of square
float speed = 0; // speed of square
float gravity = 0.1;
void setup() {
size(200, 200);
}
void draw() {
background(255);
// Draw the ball
fill(0);
noStroke();
ellipse(x, y, 10, 10);
y = y + speed;
speed = speed + gravity;
// Bounce back up!
if (y > height) {
speed = speed * -0.85;
y = height;
}
}

以下是在其代码本色的书的例子。
- 制作一个弹球的类Mover:
class Mover {
PVector location;
PVector velocity;
PVector acceleration;
float mass;
Mover(float m, float x,float y){
mass=m;
location=new PVector(x, y);
velocity=new PVector(0,0);
acceleration=new PVector(0,0);
}
void applyForce(PVector force){
PVector f=PVector.div(force, mass);
acceleration.add(f);
}
void update(){
velocity.add(acceleration);
location.add(velocity);
acceleration.mult(0); // clear everytime!!
}
void display(){
stroke(0);
fill(175);
ellipse(location.x, location.y, mass*16, mass*16);
}
void checkEdges(){
if(location.x>width){
location.x=width;
velocity.x*=-1;
}else if (location.x<0){
velocity.x*=-1;
location.x=0;
}
if(location.y>height){
velocity.y*=-1;
location.y=height;
}
}
}
- 在主程序中调用这个类生成的对象。注意是多个对象。
Mover[] movers=new Mover[10];
void setup(){
size(600,400);
for (int i=0; i<movers.length; i++){
movers[i]= new Mover(random(0.1,5),0,0);
}
}
void draw(){
background(255);
PVector wind= new PVector(0.01,0);
PVector gravity= new PVector(0,0.1);
for(int i=0; i<movers.length; i++){
movers[i].applyForce(wind);
movers[i].applyForce(gravity);
movers[i].update();
movers[i].display();
movers[i].checkEdges();
}
}
生成的效果这里就不展示了。可参考the nature of code第二章。
网友评论