Ellipse bounce from window

Hi @Ellie98,

So, I played a bit with your code. The problem is the condition and where you place it.
In your code, the if condition in the draw method changes the value of xNow and yNow, but then you calculate the verlet() and the vector stays in the same direction despite subtracting the value (I added some getters to print the position of the particle at all times).
Instead, what I did was changing the vector direction when the walls are hit. This way when hitting the wall, the particle changes to opposite direction

float damping = 0.97;
float gravityX = 0.0;
float gravityY = 0.0;
Particle p;
void setup() {
  size(600, 400);
  p = new Particle(200, 200);
  smooth();
  surface.setTitle("Billard mit der Maus");
}

void draw() {
  background(0);
  p.verlet();
  p.collision();
  p.draw();
  if (mousePressed) {
    p.getVector(mouseX, mouseY);
    p.xPrev -= p.dx;
    p.yPrev -= p.dy;
  }
  println("X = " + p.getXpos() + "\tY = " + p.getYpos());
}

class Particle {
  
  float xNow, yNow, xPrev, yPrev;
  
  float dx, dy, vx, vy, len;
  // Constructor
  Particle(float x, float y) {
    xNow = xPrev = x;
    yNow = yPrev = y;
  }
  void draw() {
    ellipse(xNow, yNow, 20, 20);
  }
    
  // velocity free movement calculation - plus calculates the direction of motion
  void verlet() {
    float tempX = xNow;
    float tempY = yNow;
    //Check the boundary conditions. If hit the walls then change direction, else keep adding to the 
    //direction. The same applies to the Y direction
    if(xNow < 0 || xNow > width) xNow -= damping * (xNow - xPrev) + gravityX;
    else xNow += damping * (xNow - xPrev) + gravityX;
    if(yNow < 0 || yNow > height) yNow-= damping * (yNow - yPrev) + gravityY;
    else yNow+= damping * (yNow - yPrev) + gravityY;
    xPrev = tempX;
    yPrev = tempY;
  }

//GETTERS
  float getXpos(){
    return xNow; 
  }
  
  float getYpos(){
    return yNow; 
  }
 
  void getVector(float x, float y) {
    vx = x - xNow;
    vy = y - yNow;
    len = dist(x, y, xNow, yNow);
  
    dx = vx / len;
    dy = vy / len;
  }
}

Hope it helps,
Best regards

1 Like