Bouncing ball with paddle

Hi, I just need it so that the ball will bounce off the two paddles. I don’t know the proper code for it.

Code:

int x,y,w,h,speedX,speedY;//circle variables
int paddleX, paddleY,paddlew,paddleH,paddleS,paddleX2,paddleY2,paddlew2,paddleH2,paddleS2;//left and right paddles variables
boolean up,down;//up down for right paddle
boolean positive, negative;//up down for left paddle
boolean a_pressed=false;//pauses game
boolean q_pressed=false;//unpauses game
int scoreL=0;
int scoreR=0;
void setup() {
  size(600,600);
  x=width/2;
  y=height/2;
  w=50;
  h=50;
  speedX=3;
  speedY=3;
  paddleX=570;
  paddleY=height/2;
  paddlew=30;
  paddleH=100;
  paddleS=5;
  paddleX2=10;
  paddleY2=height/2;
  paddlew2=30;
  paddleH2=100;
  paddleS2=5;
  
}
  void draw() {
background(0);
fill(224);
rect(paddleX,paddleY,paddlew,paddleH);
rect(paddleX2,paddleY2,paddlew2,paddleH2);
fill(255,0,0);
ellipse(x,y,w,h);
  
//moving circle
x=x+speedX;
y=y+speedY;
//preventing it leaving screen
if(x>width-w/2){
  speedX=-speedX;
}else if(x<0+w/2) {
  speedX=-speedX;
}
if(y>height-h/2){
  speedY=-speedY;
}else if(y<0+h/20){
  speedY=-speedY;
}
//moving paddle
if(up) {
paddleY=paddleY+paddleS;
}
if(positive) {
  paddleY2=paddleY2+paddleS2;
}
if(down) {
  paddleY=paddleY-paddleS;
  }
if(negative) {
  paddleY2=paddleY2-paddleS2;
}
//preventing paddle from going off screen
if(paddleY-paddleH/2<0) {
  paddleY=paddleY+paddleS;
}
if(paddleY2-paddleH2/2<0) {
  paddleY2=paddleY2+paddleS2;
}
if(paddleY+paddleH/2>height) {
  paddleY=paddleY-paddleS;
}
if(paddleY2+paddleH2/2>height) {
  paddleY2=paddleY2-paddleS2;
}
//ball bouncing off paddle
if(x<paddleX) {
  speedX=-speedX;
  }
  }
void keyPressed() {
  if(key=='d') {
    up=true;
  }
  if(key=='u') {
    down=true;
  }
  if(key=='m') {
    positive=true;
  }
  if(key=='p') {
    negative=true;
  }
  if(key=='a'){
  a_pressed=true;
  noLoop();
}
if(key=='q') {
  q_pressed=true;
  loop();
}
  }
void keyReleased() {
  if(key=='d') {
    up=false;
  }
  if(key=='u') {
    down=false;
  }
  if(key=='m') {
    positive=false;
  }
  if(key=='p') {
    negative=false;
  }
  if(key=='a'){
  a_pressed=true;
  noLoop();
}
if(key=='q') {
  q_pressed=true;
  loop();
}
}
//ball bouncing off paddle
if(x<paddleX) {
speedX=-speedX;
}

there is your problem…
you need that:

int originSpeedX = speedx;
.
.
.
void draw(){
.
.
.
//ball bouncing off paddle
if(x>paddleX - w/2 && x < paddleX+paddlew - w/2 && y < paddleY + paddleH + h/2 && y > paddleY - h/2) {
speedX=-originSpeedX;
}

//ball bouncing off paddle2
if(x>paddleX2 + w/2 && x < paddleX2 + paddlew2 + w/2 && y < paddleY2 + paddleH2 + h/2 && y > paddleY2 - h/2) {
speedX=originSpeedX;
}
}
2 Likes