Change color of ellipse when intersects

5 views
Skip to first unread message

Jack Adee

unread,
Apr 22, 2020, 11:11:09 AM4/22/20
to Processing.js
In the end I want my result to be 20 circles and if a red circle touches a yellow circle the yellow circle will turn red. Here is a scaled down version with only two. It should work but it doesn't seem too.


class Dot {
  constructor(x, y, color, speed) {
    this.x = x
    this.y = y
    this.color = color
    this.speed = speed
  }}



let x = 320;
let y = 180;
let xspeed = 5;
let yspeed = 2;
let speeds = [[5, 2], [2, 5]]
let array = [[320, 180], [450, 120]]
let colors = [[255, 0, 0], [0, 255, 255]]
let r = 10;
let dots = [new Dot(320, 180, [255, 0, 0], [5, 2]), new Dot(450, 120, [255, 255, 0], [2, 5])]
function setup() {
  createCanvas(640, 360);
}

function draw() {
  background(255);
  
  for (let i = 0; i <= 1; i++) {
    let c = color(dots[i].color[0], dots[i].color[1], dots[i].color[2]);
  noStroke();
  fill(c);
  let x = dots[i].x
  let y = dots[i].y
  ellipse(x, y, r*2, r*2);
  x += dots[i].speed[0];
  y += dots[i].speed[1];
  
  if (x > width - r || x < r) {
    dots[i].speed[0] = -dots[i].speed[0];
  }
  if (y > height - r || y < r) {
    dots[i].speed[1] = -dots[i].speed[1];
  }
  dots[i].x = x
  dots[i].y = y
  intersect(i)
  }
}

function intersect(i) {
   for (let x = 0; x < dots.length; x++) {
    if (i!==x); {
      if (x.color === [255, 0, 0]); {
        var d = dist(x.x, x.y, i.x, i.y);
        if (d < r + r) {
          i.color = [255, 0, 0]
        } else {
          return false;
        }  
    }}
  }
}



Lee Brunjes

unread,
Apr 22, 2020, 11:57:33 AM4/22/20
to proces...@googlegroups.com
So looking at your code, In draw you draw the ellipse and then pick the color using intersect.

function draw() {
  ...
  ellipse(x, y, r*2, r*2);
  ...
  intersect(i)
  }
}

Additionally, the intersect function is currently taking an int i and trying to set the color of it. and do math against it
 I would do it in a pair of nested loops, Move the intersects function into the dot class so you can be like:
for all the dots in yellow
  for all the dots in red
     if(yellow_dot.intersects(red_dot)){
      set the fill color;
      break;
    } else{
      set the fill color to something else
  }
  draw the yellow dot
after that draw all the red dots.

Does that make things easier?
-Lee








--
You received this message because you are subscribed to the Google Groups "Processing.js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to processingjs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/processingjs/c5bb8a71-9128-4291-b552-a44c3a163384%40googlegroups.com.

Jack Adee

unread,
Apr 22, 2020, 12:45:51 PM4/22/20
to Processing.js
Thanks
To unsubscribe from this group and stop receiving emails from it, send an email to proces...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages