添加“重力”会使物体最终消失
老实说我找不到错误。
移动类
class Mover {
PVector acc;
PVector loc;
PVector vel;
Mover() {
loc = new PVector(width/2, height/2);
vel = new PVector(0, 0);
acc = new PVector(0, 0);
}
void update() {
// Mouse
//PVector mouse = new PVector(mouseX, mouseY);
//mouse.sub(loc);
//mouse.setMag(0.5);
//F = M * A
vel.add(acc);
loc.add(vel);
vel.limit(2);
}
void gravity() {
PVector grav = new PVector(0, 9.8);
acc.add(grav);
}
void wind(float wind_){
PVector wind = new PVector(wind_,0);
acc.add(wind);
}
void display() {
stroke(0);
fill(0, 255, 0);
ellipse(loc.x, loc.y, 20, 20);
}
void bounce() {
if ((loc.x > width) || (loc.x < 0)) {
vel.x *= -1;
acc.x *= -1;
}
if ((loc.y > height) || (loc.y < 0)) {
vel.y *= -1;
acc.y *= -1;
}
}
void edges() {
if (loc.x > width) {
loc.x = 0;
} else if (loc.x < 0) {
loc.x = width;
}
if (loc.y > height) {
loc.y = 0;
} else if (loc.y < 0) {
loc.y = height;
}
}
}
主文件
Mover b;
void setup() {
size(800, 600);
b = new Mover();
}
void draw() {
background(255);
b.gravity();
b.wind(0.5);
b.update();
b.bounce();
//b.edges();
b.display();
}
我希望球最终会停留在屏幕底部
我得到的是它最终消失了。
新的帮助程序使发布变得更容易,这使我对这个问题有了更多的了解,但是我所说的只是我必须说的
答案 0 :(得分:0)
当检测到与地面或天花板的碰撞时,则必须将球的位置限制在窗口的范围内:
class Mover {
// [...]
void bounce() {
// [...]
if ((loc.y > height) || (loc.y < 0)) {
vel.y *= -1;
acc.y *= -1;
loc.y = loc.y > height ? height : 0; // limit y in the range [0, height]
}
}
}
由于重力不断加到加速度矢量(b.gravity();
)上,因此如果位置低于地面,球将稍微移至无位置。请注意,如果速度矢量(vel
)太小而无法将球提升到地面上方,则条件loc.y > height
再次满足,并且加速度acc.y *= -1
再次转向。
一种选择是修复方法边缘:
class Mover {
// [...]
void edges() {
if (loc.x > width) {
loc.x = width;
} else if (loc.x < 0) {
loc.x = 0;
}
if (loc.y > height) {
loc.y = height;
} else if (loc.y < 0) {
loc.y = 0;
}
}
并通过在draw()中调用b.edges()
来限制球的位置:
void draw() {
background(255);
b.wind(0.5);
b.gravity();
b.update();
b.bounce();
b.edges();
b.display();
}