Objects Sense when they Touch each other

The idea is that when 2 green objects touch each other both of them change to red. Unfortunately, this only works for the last 2 objects. When an object touches another object (but the last one) it doesn't change color, and when it touches the last one it changes to red, but the last object does not.

I don't know if the error is in the nested loop or in another place. Can you help me? Thanks :)

int numPer =4;
Personas[] per = new Personas[numPer];

void setup(){
  size(400,400);
  frameRate(60);
  background(0);
  for (int i = 0 ; i<per.length;i++){
    //Personas(x,y,radius)
    per[i] = new Personas((width/(numPer*2))*((i*2)+1),height-(height/6),25);
  }
}//setup

void draw(){
  background(0);
    for(int i =0; i<per.length; i++){ //itself
      per[i].arrastrar();
      for(int j =0; j<per.length; j++){ //another object
        if (i != j){ //excludes itself from the test
          if (per[i].overlaps(per[j])){ 
            fill(255,0,0); 
          }
          else { 
            fill(0,255,0); 
          }
        } 
      }
      per[i].ver();
    }
}//draw


class Personas {
  PVector mouse;
  PVector pos;
  int radio;

  Personas(float x, float y, int radio_) {
    pos = new PVector(x,y);
    radio = radio_;
  }

  //to drag the object with the mouse
  void arrastrar(){ 
    mouse = new PVector(mouseX,mouseY);
    float distMouse = dist(pos.x,pos.y,mouse.x,mouse.y);
    println(pos.x);
    if(mousePressed && (distMouse < radio) ){
      pos = new PVector(mouseX,mouseY);
    }
  }

  //Tests if overlaps
  boolean overlaps(Personas otra){
    float d = pos.dist(otra.pos);
    if( (d < radio + otra.radio) ){ return true; }
    else { return false; }
  }

  //display
  void ver(){
    ellipseMode(RADIUS);
    ellipse(pos.x,pos.y,radio,radio);
  }
} //class

Answers

  • You do lot of fill() in the loop, some contradicting the others. Then you draw with the last called fill.
    You should instead set a boolean variable ("is this persona touching another"), the call the proper fill before drawing the circle.

  • edited April 2015 Answer ✓

    @DanObscur==

    in order to understand what happens set (with your code) frameRate(3); in order to avoid that, simply add "break" in the loop:

            if (per[i].overlaps(per[j])){ 
                        fill(255,0,0);
            break;
            }else{
            fill(0,255,0);
            }
    

    ....

  • edited April 2015

    or you can just break out of the (inner) loop if it's touching one of the others

  • @akenaton

    But why do I need break;? Is it not implied in the if(per[i].ovelaps(per[j])) statement that otherwise true it should be run the code in the else block?

  • i have told you:: set frameRate(1) && see...

Sign In or Register to comment.