Handling a strange problem with float

I tried to figure this out for hours, but to no avail. This is a fairly simple code, a bouncing ball (particle). Initializing the particle velocity to (0, 0) will support its bouncing up and down. Changing the initial particle velocity to (0, 0.01) or any decimal float will reduce the ball

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;
    }
  }
}
+4
source share
1 answer

I am not a specialist in vector processing, but I believe that I understand why this is happening. If you try to recreate this problem with different values ​​of the y-part of the velocity vector, you will find that this happens only when the values ​​are not multiple .5. Based on this, probably this line answers:

if (pos.y > height ) {
  vel.y *= -1;
  pos.y = height;
}

. , 0 , , , , , , . , .5 0, . , , :

if (pos.y >= height ) {
  vel.y *= -1;
  pos.y = height;
}

, 0 . , .

+5

Source: https://habr.com/ru/post/1671032/


All Articles