#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How to make these balls bounce apart once they collide in p5.js? (multiple ball collision)

Hello guys, I would like to make these balls bounce apart once they collide into each other( with Arrays). So how do I do that? Here's my code.

``````var x = [];
var y = [];
var xspd = [];
var yspd = [];
var xdir = [];
var ydir = [];

function setup() {
createCanvas(500, 300);

for (var i = 0; i < 10; i++) {
x[i] = random(width);
y[i] = random(height);
xspd[i] = random(1, 5);
yspd[i] = random(1, 5);
xdir[i] = 1;
ydir[i] = 1;
}

}

function draw() {
background(0);

move();
display();
}

function move() {
for (var i = 0; i < 10; i++) {
x[i] = x[i] + xspd[i] * xdir[i];
y[i] = y[i] + yspd[i] * ydir[i];

xdir[i] *= -1;
} else if (x[i] > width - radius) {
xdir[i] *= -1;
}

ydir[i] *= -1;
} else if (y[i] > height - radius) {
ydir[i] *= -1;
}
}

}

function display() {
for (var i = 0; i < 10; i++) {
noStroke();
fill(255, 255, 0);
}
}
``````

• This is a fairly standard requirement. What have you tried so far?

• It'd be a good idea to convert all of those arrays into 1 class too!
These Daniel Shiffman below can teach ya that: :-bd
https://Vimeo.com/channels/learningp5js/

• I have tried this so far, but there is bug.

``````<html>

<meta charset="UTF-8">
<script src="http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>

<script>
var x = [];
var y = [];
var xspd = [];
var yspd = [];
var xdir = [];
var ydir = [];

function setup() {
createCanvas(500, 300);

for (var i = 0; i < 10; i++) {
x[i] = random(width);
y[i] = random(height);
xspd[i] = random(1, 5);
yspd[i] = random(1, 5);
xdir[i] = 1;
ydir[i] = 1;
}
}

function draw() {
background(0);

bounce();
display();

}

function distance(x1, x2, y1, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
var d = sqrt(dx * dx + dy * dy);
return d;
}

function bounce() {
for (var i = 0; i < 10; i++) {
x[i] = x[i] + xspd[i] * xdir[i];
y[i] = y[i] + yspd[i] * ydir[i];

xdir[i] *= -1;
} else if (x[i] > width - radius) {
xdir[i] *= -1;
}

ydir[i] *= -1;
} else if (y[i] > height - radius) {
ydir[i] *= -1;
}

for (var k = i + 1; k < 10; k++) {
xdir[k] *= -1;
ydir[k] *= -1;
}
}
}
}

function display() {
for (var i = 0; i < 10; i++) {
noStroke();
fill(255, 204, 0,90);