使用float处理奇怪的问题

Kev*_* Li 4 processing

我一直试图弄清楚这几个小时现在无济于事.这是一个非常简单的代码,一个弹跳球(粒子).将粒子的速度初始化为(0,0)将使其上下弹跳.将粒子的初始化速度更改为(0,0.01)或任何十进制浮点数将导致球减少

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Unk*_*ble 5

我不是处理载体的专家,但我相信我已经弄清楚为什么会这样.如果您尝试使用速度向量的y部分的不同值重新创建此问题,您会发现它仅在值不是.5的倍数时发生.基于此,这条线可能是负责的:

if (pos.y > height ) {
  vel.y *= -1;
  pos.y = height;
}
Run Code Online (Sandbox Code Playgroud)

该线围绕球的高度,并反转球的速度.当球准确地击中0并且在它恢复之前获得额外的速度时,这可以正常工作,但是当球稍微低于它应该的时候,来自额外迭代的速度不会被添加.实际上,.5的倍数恰好为0,但其他值则不然.我的证据是,当您将违规代码更改为以下内容时,每个值都会导致球最终落到地面:

if (pos.y >= height ) {
  vel.y *= -1;
  pos.y = height;
}
Run Code Online (Sandbox Code Playgroud)

简而言之,当它达到0时,圆形并且不使球反弹导致此问题.我希望这能回答你的问题.