I need help with randomizing (javascript)

//tells collision of ball with paddle
void contactPaddle() {
//left paddle collision with ball
if(x - w/2 < paddleXL + paddleW/2 && y - h/2 < paddleYL + paddleH/2 && y + h/2 > paddleYL - paddleH/2) {
if(speedX < 0) {
speedX = -speedX;
}
}
//right paddle collision with ball
else if(x + w/2 > paddleXR - paddleW/2 && y - h/2 < paddleYR + paddleH/2 && y + h/2 > paddleYR - paddleH/2) {
if(speedX > 0) {
speedX = -speedX;
}
}
}

This is the code i’m using for creating collision between my ball and paddle in a pong game. Im trying to figure out how to randomize which direction . the ball goes after touching the paddle to make it more difficult. Anyone have an idea?

1 Like

If you already have a speedY variable you could simply add a line like

// under speedX = -speedX;
speedY += random(-speedX/10, speedX/10);

Though I would suggest trying to make the ball it’s own class like the particle class seen in 4.2 example of nature of code. It would make it much easier to add a random PVector as a force whenever there is a collision. The Nature of Code is a great book for learning to make more believable physics and all the examples are written in processing.

Note: In future please format your code in processing using Ctrl+t and paste it here with the ``` ``` signs like:

type or paste code here

It makes it much easier to read and understand.

1 Like