top drop menu

Recent Post

화요일, 11월 15

프로세싱(10) - 배열로 만드는 다량의 바운싱 볼 만들기

볼 클래스를 만들고 바닥에서 튕겨 올라 무한 반복 되게 한다. 이제 배열을 이용해서 다량의 볼을 복제해서 움직이도록 만들어 보자.


int num = 100;
//선언
Ball[] balls = new Ball[num];

void setup() {
  size(740, 400);
  background(0);
  //총갯수만큼 반복해서 객체생성후 배열에 담는다.
  for (int i = 0; i < balls.length; i++) {
    balls[i] = new Ball();
  }
}


void draw() {
  background(0);
  //객체 - 액션
  for (int  i = 0; i < balls.length; i++) {
    balls[i].update();
    balls[i].display();
  }
}

//클래스 정의
class Ball {
  //변수
  float x, y;
  float r;
  float g;
  float speedx, speedy;
  color c;
  
  //생성자
  Ball() {
    x = random(width);
    y = random(height/2);
    r = 10; //볼의 반지름
    g = random(0.01, 0.04);
    speedx = random(-1, 1);
    speedy = 0;
    c = color(random(255), random(255), random(255));
  }
  
  //액션
  void update() {
    x = x + speedx;
    y = y + speedy;
    
    speedy = speedy + g; //중력을 추가해 준다.
    
    
    //경계에 부딪히면 반전되게 ...
    if (x > width - r ) { 
      x = width -r;
      speedx *= -1;
    } else if( x < r) {
      x = r;
      speedx *= -1;
    }
    
    if (y > height - r) {
      y = height - r;
      speedy *= -1;
    } else if ( y < r) {
      y = r;
      speedy *= -1;
    }
    

  }
  
  //화면에 그린다.  
  void display() {

    noStroke();
    fill(c);
    ellipse(x, y, r * 2, r * 2);
  }
}


----------

주석을 참고 하면 쉽게 이해 할 수 있다. 램덤함수를 이용해서 각각의 움직임에 차이를 주었다. 실행해 보자.


Blogger Widget