Bouncing Ball Velocity Problem

I’m new to Processing (I programmed in C# before) and I tried to make a bouncing ball with vectors but when I run the program, the ball goes a little bit to the right.
This is my code:

Ball b;

void setup() {
  size(1280, 720);
  b = new Ball(0, height/2, 3, 2, 30);
}

void draw() {
  background(0);
  b.Display();
  b.Update();
  b.Limit(4);
  b.Bounce();
}

and my Ball class;

class Ball {

  PVector pos, vel, acceleration;
  float radius;

  Ball(float x, float y, float spdx, float spdy, float size) {
    pos = new PVector(x, y);
    vel = new PVector(spdx, spdy);
    acceleration = new PVector(-0.01, 0.1);
    radius = size/2;
  }

  void Update() {
    vel.add(acceleration);
    pos.add(vel);
  }
  void Display() {
    circle(pos.x, pos.y, radius*2);
  }
  void Limit(float max) {
    if (max > 10) {
      vel.normalize();
      vel.mult(max);
    }
  }
  void Bounce() {
    if (pos.x < 0 || pos.x > width) {
      vel.x = vel.x * -1 + 0.5;
    }
    if (pos.y < 0 || pos.y > height) {
      vel.y = vel.y * -1 + 0.5;
    }
  }
}

I can’t find a solution to problem, despite my tries, so is there a solution?
Thanks!
(I’m French, so sorry for my english)

here is the issue.When I combined your code, it continuously went to the right. It is because you see acceleration PVector to -0.01,0.1. -0.01 is the force pushing the ball to the left and the 0.1 is the gravity

1 Like

Yes, it works now!
Thanks!

1 Like