topical media & game development

talk show tell print

graphic-processing-algorithm-Ch06-p144-MyElement.pde / pde



  
  class MyElement{
    int id;
    int size = 10;
    float xpos = 0.;
    float ypos = 0.;
    float friction = 0.05;
    float xspeed = 0;  // Speed of the shape
    float yspeed = 0;  // Speed of the shape
    MyElement[] others;
  
    MyElement(int idin, MyElement[] othersin){
      id = idin;
      others = othersin;
    }
  
    void move() {
      xpos += xspeed;
      ypos += yspeed;
      if (xpos  > width) xspeed *= -1; 
      else if (xpos < 0) xspeed *= -1;
      if (ypos > height) yspeed *= -1;  
      else if (ypos < 0) yspeed *= -1;
      xpos = constrain(xpos, 0, width);
      ypos = constrain(ypos, 0, height);
      ellipse(int(xpos),int(ypos),size,size);
    }
  
    void collide() {
      for (int i = id + 1; i < nelements; i++) {
        if (dist(xpos,ypos,others[i].xpos,others[i].ypos) < 2*size) { 
          float angle = atan2(others[i].ypos - ypos, others[i].xpos - xpos);
          float targetX = xpos + cos(angle)*2*size ;
          float targetY = ypos + sin(angle)*2*size ;
          float ax = (targetX - others[i].xpos) * friction;
          float ay = (targetY - others[i].ypos) * friction;
          xspeed -= (ax);
          yspeed -= (ay);
          others[i].xspeed += (ax);
          others[i].yspeed += (ay);
        }
      }   
    }
  }
  
  


(C) Æliens 04/09/2009

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.