본문 바로가기
p5.js

[p5.js] 4. The Nature of Code, Random Walker, Vector

by 쿠킷리스트 2021. 9. 13.

학습내용(The Nature of Code/Kadenz.com)

Random Walker

  • OOP : Obejct Orientation Programming
  • 오브젝트를 만들고, 오브젝트 x, y 좌표로 로케이션 표시.
  • 모든 세션은 오브젝트를 만들고 함수를 call(선언?)하는 순서로 이뤄질 것.

var w; // var w = new Walker();는 왜 안될까?

function setup() {
  createCanvas(640, 360); // 캔버스 생성
  w = new Walker(); // 객체 생성
}

function draw() {
  background(51); //캔버스 색 지정
  w.display(); //display에 접근
}

function Walker() {
  this.x = width/2; // this는 Walker를 말하고
  this.y = height/2; // x,y좌표를 나타냄

  this.display = function() {
    fill(255); // Walker의 색
    ellipse(this.x, this.y, 48, 48); //Walker의 위치와 세로 가로 지름
  }
}

궁금한 점

  • new는 무엇인고 어디에 쓰이는 것인가? 해결
  • w.display( );가 계속 에러가 나는데 왜 이러는 걸까?
  • 1번 줄에 var w; 를 var w = new Walker();로 바꾸면 안될까?
    • setup() 부분에 w = new Walker();를 지우고 1번 줄에 옮겨적으면 에러가 나는데 왜 그런걸까?
    • 코딩 순서?에 대한 공부가 필요하다.
  • 온점은 무슨 역할이고 어떻게 사용되는 것인가?

분명히 똑같이 쓴 것 같은데... 무엇이 다른 걸까

추가 공부를 통해 알게 된 점

  • property에 function이 담겨있다면 그것을 method라 부름.
  • constructor(생성자)는 객체를 만드는 역할을 하는 함수. 'new 함수'를 사용할 때 함수가 아니라 생성자라 부름. new를 사용할 경우 객체를 생성하여 객체를 반환함.

function draw() {
  background(51);
  w.walk(); //walk에 접근할 수 있도록
  w.display();
}

function Walker() {
  this.x = width/2; 
  this.y = height/2; 
  
  this.walk = function(){ //랜덤 이동값 추가
    this.x = this.x + random(-5, 5)
    this.y = this.y + random(-5, 5)
  }

p5.js에서의 Vector(벡터)

  • point A ------------------------ point B
  • Vector is instructions how to get from point A to point B
var x = 100;
var y = 50;
var v = createVector(100, 50);
  • 벡터를 사용하면 위와 같이 두번 쓸 내용을 한 번에 요약해서 쓸수 있음.
function Walker() {
  this.pos = createVector(width/2, height/2);
  // this.x = width/2; 
  // this.y = height/2; 
  
  this.walk = function(){ 
    this.pos.x = this.pos.x + random(-5, 5)
    this.pos.y = this.pos.y + random(-5, 5)
  }
  this.display = function() {
    fill(255); 
    ellipse(this.pos.x, this.pos.y, 48, 48); 
  }
  • 두줄로 표현하고 있던 코드를 한줄로 줄이고 x, y 좌표를 표시하는 코드들에 pos를 추가하면서 똑같은 기능을 구현.

p5.js에서의 Vector math(벡터 계산)

x = x + random(-1, 1)
y = y + random(-1, 1)

pos.x = pos.x +______
pos.y = pos.y +______

5 + 2 = 7
"a" + "bc" = "abc"
  • reference에서 p5.Vector의 다양한 함수에 대해서 확인할 수 있음.
  • v3 = v1 + v2 라고 했을 때, v3는 시작점에서 v1 만큼 이동한 이후 v2 만큼 이동한 지점까지의 이동을 나타낸다.
  • + : add( ) / - : sub( ) / * : mult( )
function Walker() {
  this.pos = createVector(width/2, height/2);
  
  this.walk = function(){ 
    this.vel = createVector(random(-5, 5), random(-5, 5))
    this.pos = this.pos.add(this.vel);//벡터 값에 벡터를 더하는 방법
    
    // this.pos = this.pos + this.pos + this.vel;
    // this.pos.x = this.pos.x + random(-5, 5)
    // this.pos.y = this.pos.y + random(-5, 5)
  }

p5.js에서의 Building a physics engine(물리 엔진 구축)

pos.add(vel)
vel.add(acc)
  • 오브젝트의 포지션은 vel(속도)에 의해 결정되고 vel(속도)은 acc(가속도)에 의해서 결정된다.
  • acc가 vel에 영향을 미치고, vel이 pos에 영향을 미치는 구조.

function draw() {
  background(51);
  w.update(); 
  w.display();
}

function Walker() {
  this.pos = createVector(width/2, 0);
  this.vel = createVector(0, 0);
  this.acc = createVector(0, 0.1);
  
  this.update = function(){ 
    this.vel.add(this.acc);
    this.pos.add(this.vel);
  }
  this.display = function() {
    fill(255); 
    ellipse(this.pos.x, this.pos.y, 48, 48); 
  }
  • 가속도가 붙은 것을 확인할 수 있다.

느낀 점

 시간 가는 줄 모르고 공부? 했다. 공부라는 생각이 들지 않았다. 올 추석 연휴 때 결제를하고 The Nature of Code session1 뒷부분을 열람해야겠다.

 내 기준에서 조금만 긴 코드를 보면 패닉 상태였는데 하나하나씩 뜯어보면 충분히 이해할 수 있었다. 조금 답답한 점은 원리, 구조, 개념 등이 궁금하다는 것이다. 예를 들어 this.pos에서 ' . '의 역할이 무엇인지, w = new walekr( );에서 'new'는 무슨 역할인지 작동되는 원리는 무엇인지 등이 발목을 잡는다. 구글링이나 유튜브를 통해 관련 내용을 검색하고 찾아보는데, 어느정도 이해는 하겠으나 완벽히 내것으로 만들기가 쉽지 않다. javascript 기초를 따로 공부해야할 필요성을 느낀다.

댓글