[Nature of Code] processing 5. 힘 생성

2023. 2. 2. 03:03
반응형

챕터 2.5 (113p)

 

Mover[] movers = new Mover[100];

void setup() {
  size(300, 300);
  for(int i=0; i<movers.length; i++) {
    movers[i] = new Mover(random(0.1, 5), 0, 0);
  }
}

void draw() {
  background(155);
  
  //2개의 힘을 만들어줌
  PVector wind = new PVector(0.01, 0);
  PVector gravity = new PVector(0, 0.1);
  
  for(int i=0; i<movers.length; i++){
    //배열에 있는 각 객체에 힘을 적용해줌
    movers[i].applyForce(wind);
    movers[i].applyForce(gravity);
    
    movers[i].update();
    movers[i].display();
    movers[i].checkEdges();
  }
}

class Mover {
  PVector location;
  PVector velocity;
  PVector acceleration;
  float mass;
  
  Mover(float m, float x, float y){
    mass = m;
    location = new PVector(x, y);
    velocity = new PVector(0,0);
    acceleration = new PVector(0,0);
  }
  
  //뉴턴의 운동 2법칙
  void applyForce(PVector force){
    //힘을 매개변수로 받고, 질량으로 나눠주고, 가속도에 더해줌
    PVector f = PVector.div(force, mass);
    acceleration.add(f);
  }
  
  void update(){
    //기본적인 움직임
    velocity.add(acceleration);
    location.add(velocity);
    
    //순간순간 가속도를 초기화함
    acceleration.mult(0);
  }
  
  void display(){
    stroke(0);
    fill(175);
    
    //질량만큼의 크기로 객체를 그려줌
    ellipse(location.x, location.y, mass*16, mass*16);
  }
  
  //모서리에 닿으면 객체가 튕기도록 함
  void checkEdges() {
    if(location.x > width){
      location.x = width;
      velocity.x *= -1;
    } else if(location.x < 0){
      location.x *= -1;
      location.x = 0;
    }
    if(location.y > height) {
      //모서리에 닿으면 속도를 반대방향으로 만들어, 튕기는 것처럼 구현
      velocity.y *= -1;
      location.y *= height;
    }
  }
}

 

결과물

 

 

반응형

BELATED ARTICLES

more