4
我一直試圖弄清楚現在幾個小時無濟於事。這是非常簡單的代碼,一個彈跳球(粒子)。將粒子的速度初始化爲(0,0)將保持它上下跳動。顆粒的初始化速度更改爲(0,0.01)或任何十進制浮點將導致球降低用float處理奇怪的問題
Particle p;
void setup() {
size(500, 600);
background(0);
p = new Particle(width/2, height/2);
}
void draw() {
background(0, 10);
p.applyForce(new PVector(0.0, 1.0)); // gravity
p.update();
p.checkBoundaries();
p.display();
}
class Particle {
PVector pos, vel, acc;
int dia;
Particle(float x, float y) {
pos = new PVector(x, y);
vel = new PVector(0.0, 0.0);
acc = new PVector(0.0, 0.0);
dia = 30;
}
void applyForce(PVector force) {
acc.add(force);
}
void update() {
vel.add(acc);
pos.add(vel);
acc.mult(0);
}
void display() {
ellipse(pos.x, pos.y, dia, dia);
}
void checkBoundaries() {
if (pos.x > width) {
pos.x = width;
vel.x *= -1;
} else if (pos.x < 0) {
vel.x *= -1;
pos.x = 0;
}
if (pos.y > height) {
vel.y *= -1;
pos.y = height;
}
}
}