# I need help with randomizing (javascript)

**URL:** https://discourse.processing.org/t/i-need-help-with-randomizing-javascript/6704
**Category:** Coding Questions
**Created:** [December 17, 2018, 2:04pm UTC](https://discourse.processing.org/t/i-need-help-with-randomizing-javascript/6704 "2018-12-17T14:04:41Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Wuoahter](https://avatars.discourse-cdn.com/v4/letter/w/e8c25b/32.png) [@Wuoahter](https://discourse.processing.org/u/Wuoahter)
#### Post date: [December 17, 2018, 2:04pm UTC](https://discourse.processing.org/t/i-need-help-with-randomizing-javascript/6704/1 "2018-12-17T14:04:41Z")

</div>

//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?

---

<div class="post-metadata">

### Author: ![figraham](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/figraham/32/4161_2.png) [@figraham](https://discourse.processing.org/u/figraham)
#### Post date: [December 17, 2018, 8:48pm UTC](https://discourse.processing.org/t/i-need-help-with-randomizing-javascript/6704/2 "2018-12-17T20:48:22Z")

</div>

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

```auto
// 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](https://natureofcode.com/book/chapter-4-particle-systems/). 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:

```auto
type or paste code here

```

It makes it much easier to read and understand.
