Collision | Pong Help

Hello, can you help me how to do collision so when the ball hits the paddle, it will go back?

The code >

float x = 400;
float y = 300;
float k = width - 20;
float e = height / 2;
float c = 715;
float h = height / 2;
float xSpeed = 3.3;
float ySpeed = 3.3;

void setup() {
  size(800, 600);
}

void draw() {
  fill(0, 10);
  noStroke();
  smooth();
  rect(0, 0, width, height);
  
  x = x + xSpeed;
  
  fill(255);
  ellipse(x, y, 20, 20);
  
  rect(k, e, 10, 100);
  rect(c, h, 10, 100);
  
  if(e > height - 110) {
    e = height - 110;
  }
  if(e < 0) {
    e = 0;
  }
    if(h > height - 110) {
    h = height - 110;
  }
  if(h < 0) {
    h = 0;
  }
  if(x > width) {
    xSpeed = xSpeed * -1;
  }
  if(x < 0) {
    xSpeed = xSpeed * -1;
  }
}

void keyPressed() {
  if(keyPressed) {
    if(key == 'w') {
      e = e - 11;
    }
  }
  if(key == 's') {
    e = e + 11;
}
    if(keyCode == UP) {
      h = h - 11;
    }
  if(keyCode == DOWN) {
    h = h + 11;
}
}
1 Like

Sure

first check if the y pos of the ball is inside the paddle (y>paddle1y && y<paddle1y+100)

And x is near paddle surface

  • if so, say xSpeed = xSpeed * -1;

  • if not, restart game / ball

AND delete

  if (x > width) {
    xSpeed = xSpeed * -1;
  }
  if (x < 0) {
    xSpeed = xSpeed * -1;
  }

because it lets the ball return when NOT inside the paddle

Remark 1

Add y = y + ySpeed;

Remark 2

And please

  rect(k, e, 10, 100);
  rect(c, h, 10, 100);

make better names for your variables such as

  • paddle1X, paddle1Y
  • paddle2X, paddle2Y

Chrisir

2 Likes

You might want to initialize some of your global variables (such as k, e, and h) inside your setup instead. To understand why, add this line of code under size(800, 600); :

println(k);
3 Likes