We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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 = [];
var radius = 15;
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];
if (x[i] < radius) {
x[i] = radius;
xdir[i] *= -1;
} else if (x[i] > width - radius) {
x[i] = width - radius;
xdir[i] *= -1;
}
if (y[i] < radius) {
y[i] = radius;
ydir[i] *= -1;
} else if (y[i] > height - radius) {
y[i] = height - radius;
ydir[i] *= -1;
}
}
}
function display() {
for (var i = 0; i < 10; i++) {
noStroke();
fill(255, 255, 0);
ellipse(x[i], y[i], radius * 2, radius * 2);
}
}
Answers
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.
What is the bug? Looking at the code I suspect you may have a problem with balls getting stuck together; but I shouldn't have to run the code to confirm this: you want help so describe the problem properly...