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;
}
}
}