[Nature of Code] processing 3. 속도/가속도와 벡터를 활용한 이동

2023. 2. 1. 00:02
반응형

속도와 벡터를 활용한 이동

Mover mover;

void setup() {
  size(200, 200);
  smooth();
  
  // Mover 클래스로 객체를 생성
  mover = new Mover();
}

void draw(){
  background(187);
  
  //Mover 객체의 함수 호출
  mover.update();
  mover.checkEdges();
  mover.display();
}

class Mover {
  PVector location;
  PVector velocity;
  
  Mover() {
    location = new PVector(random(width), random(height));
    velocity = new PVector(random(-2,2), random(-2,2));
  }
  
  void update() {
    //중요한 부분! 속도로 위치를 변경한다.
    location.add(velocity);
  }
  
  void display() {
    stroke(0);
    fill(33);
    ellipse(location.x, location.y, 16, 16);
  }
  
  void checkEdges() {
    if(location.x > width) {
      location.x = 0;
    }
    else if (location.x < 0){
      location.x = width;
    }
    
    if(location.y > height) {
      location.y = 0;
    }
    else if (location.y < 0){
      location.x = height;
    }
  }
}

 

결과물

 

 

 

가속도와 벡터를 활용한 이동

 

Mover mover;

void setup() {
  size(200, 200);
  smooth();
  
  // Mover 클래스로 객체를 생성
  mover = new Mover();
}

void draw(){
  background(187);
  
  //Mover 객체의 함수 호출
  mover.update();
  mover.checkEdges();
  mover.display();
}

class Mover {
  PVector location;
  PVector velocity;
  PVector acceleration; //추가된 부분
  
  Mover() {
    location = new PVector(width/2, height/2); //수정된 부분(일단 Mover를 화면 중앙에 위치시킴)
    velocity = new PVector(0, 0); //수정된 부분(속도를 0으로 만든다)
    acceleration = new PVector(-0.001, 0.01); //가속도를 부여한다
    velocity.limit(10); //추가된 부분(너무 빨라지지 않게 속도에 제한을 걸어줌)
  }
  
  void update() {
    velocity.add(acceleration); //추가된 부분
    location.add(velocity);
  }
  
  void display() {
    stroke(0);
    fill(33);
    ellipse(location.x, location.y, 16, 16);
  }
  
  void checkEdges() {
    if(location.x > width) {
      location.x = 0;
    }
    else if (location.x < 0){
      location.x = width;
    }
    
    if(location.y > height) {
      location.y = 0;
    }
    else if (location.y < 0){
      location.x = height;
    }
  }
}

 

결과물

 

가속도(acceleration)의 값인 -0.001, 0.01이 너무 작아보일 수 있지만,

프로세싱은 1초에 30분 draw() 함수를 실행한다.

따라서 1초에 30번 속도에 가속도가 더해지는 것이므로, 속도는 순식간에 빨라지게 된다.

반응형

BELATED ARTICLES

more