How to change a circle's colour when the mouse hovers it?

New to Processing. I know I’m supposed to check if the distance from the mouse to the circle is less than the radius, but I don’t know how to write the code for that or where to place it. This code below is just an adapted version I copied from a Daniel Shiffman tutorial.

var circles = [];

 setup = () => {
    createCanvas(2120, 1225);
 }
     
draw = () => {
    
    for (var c = 0; c < 2100; c++) {
        var circle = {
        x: random(width),
        y: random (height),
        r: random (80, 10)  
        };
        

        
        
        var overlap = false;
        
        var protection = 0;
        
        for (var j = 0; j < circles.length; j++){
            var other = circles[j];
            var d = dist(circle.x,circle.y, other.x, other.y);
            if (d < circle.r + other.r){
            overlap = true;
            }
        }
        
        if (!overlap) {
        circles.push(circle);
        }
        
        protection++;
        if (protection > 10000) {
            break;
        }
    }
    
    
    for (var i = 0; i < circles.length; i++){
        fill(255,255,255);
        strokeWeight(2);
        ellipse(circles[i].x, circles[i].y, circles[i].r*2, circles[i].r*2);
        
                
        }
    
    
   
    }
1 Like

Click on link above to view thread. Solution – syntax and placement – and importantly an explanation appears in the posts from @Chrisir

2 Likes

question why don’t you just use a class object for circle?
I think this code will help with what you want to do.

in sketch.js

var circles = [];

function setup() {
  createCanvas(600, 600);
}

function draw() {
  background(220);
  for (var i = 0; i < circles.length; i++){
    circles[i].check();
    circles[i].show();
  }
}

function mousePressed(){
  var c = new Circle();
  circles.push(c);
}

in circle.js

class Circle{// this creates a class
  constructor() {
    this.x = random(width);
    this.y = random (height);
    this.r = random (80, 10) ;
    var overlap = false;
  }
  
  check(){
    var d = dist(this.x,this.y,mouseX,mouseY);
    if (d < this.r){this.overlap = true;}
    else {this.overlap = false;}
  }
  
  show(){
    fill(255,0,0);
    if (this.overlap){fill(0,255,0);}
    ellipse(this.x,this.y,this.r);
  }
}

in index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="sketch.js"></script>
    <script src="circles.js"></script>
  </body>
</html>

if need me to explain it just ask

1 Like
2 Likes