doesn't work

var balls = []; var n = 20; var d;

function setup() { createCanvas(710,400); for(i = 0; i < n; i++) { balls.push(new Ball()); } textAlign(CENTER); }

function draw() { background(189); for(i = 0; i < balls.length; i++){ balls[i].x = random(balls[i].x - 1, balls[i].x + 1); balls[i].y = random(balls[i].y - 1, balls[i].y + 1); for(z = 0; z < balls.length; z++){ if(dist(balls[i].x, balls[i].y, balls[z].x, balls[z].y) < 30){ balls[z].col = 100; } } balls[i].display(i); }


function Ball(){

    this.x = random(15, width - 15);
    this.y = random(15, height - 15);
    this.col = 255;

    this.display = function(num) {
        ellipse(this.x, this.y, 30);
        text(num, this.x, this.y + 5);


I want the balls to change color only when the distance between them is under 30 (basically when they're touching). Somehow they all change color. Why?


  • Your forum discussion title could be a little more descriptive of what your sketch is. If everyone had a title of "Help! Doesn't work!" we'd never be able to find anything. You can't fix it now, but don't get it wrong next time.

    The code you posted is not formatted properly for the forums. Go and find the sticky thread (It's one of the top three discussions...) that tells you how to format it properly. You can fix this: Edit your post, select your code, press ctrl + o.

    I suspect the issue is how you are determining overlaps, but aren't going to even try to copy and paste and run your code until you fix the formatting so I can do so easily.

  • Yes, format the code.

    Try printing the values of i and z and the distance between them when the balls change colour...

Sign In or Register to comment.