본문 바로가기
p5.js

[p5.js] 4-1. Random Walk, OOP, Class

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

학습내용(Random Walk)

  • 반복문에서 반복의 횟수를 이해 해보자

Random Walk

  • Random Walk는 과학 분야에서 발견되었고 이후 예술계에도 반영되었다.
  • Brownian motion(브라운 운동) : 아인슈타인이 분자와 입자를 이해하게되는 계기
let x = 10;
let y = 30;
  • 선언과 값을 할당하는 것을 동시에 할 수 있다.
//values for walker
let x, y; //전역 변수
let w;


function setup() {
  createCanvas(400, 400); 
  
  let L; //지역 변수
  
  //setup values
  x = width/2;
  y = height/2;
  w = 10;
}
  • 네이밍 스코프 안에서 변수를 선언해주는 것은 함수 안에서만 읽을 수 있다.(지역변수)
  • 네이밍 스코프 밖에서 변수를 선언해주는 것은 전역변수.
  • 온점이 찍혀있으면 객체 안의 무언가에 명령을 하고 있다고 생각.

궁금한 점

  • 절차 지향과 객체 지향의 차이가 무엇인가?
  • Functional Paradigm(함수형 패러다임)이란 무엇인가?
  • 왜 let x, y는 한줄에 let w는 다른 줄에 입력한 것인가?(구분하기 위해서?)
  • Class는 무엇인가.

필요한 점

  • 자바스크립트 문맥을 이해할 수 있어야한다.

Random Walk 변형

let ball;


function setup() {
  createCanvas(400, 400); 
  ball = new Walker();
}


function draw() {
  background(220, 5);
  ball.update();
  ball.display();
}


// new way to define Object
class Walker {
  //setup values
  constructor() {
  	this.x = width/2;
  	this.y = height/2;
  	this.w = 10;
  }
  
  update() {
    //update position
  	this.x = this.x + random(-5, 5);
  	this.y = this.y + random(-5, 5);
  }
  
  display() {
    //display walker
    stroke(0);
    fill(random(1,255), random(1,255), random(1,255));
    textSize(50);
	ellipse(this.x, this.y, random(1,30), random(1,30));
	stroke(random(1,255), random(1,255), random(1,255));
    line(200, 0, this.x, this.y);
   
  }
}
  • 기존의 random walk 예제에서 원의 크기를 변형시켜주고 싶었다.
  • circle이 아니라 ellipse라서 타원을 만들 수 있었고 세로, 가로 길이를 랜덤하게 만들었다.
  • line을 생성해 ellipse를 추처럼 만들고자 했다.
  • line, ellipse 모두 색을 랜덤으로 지정해주었다.

서서히 색 변하기(그라데이션)

class Walker {
  //setup values
  constructor() {
  	this.x = width/2;
  	this.y = height/2;
  	this.w = 10;
    this.i = 0;
  }
  
  update() {
    //update position
  	this.x = this.x + random(-5, 5);
  	this.y = this.y + random(-5, 5);
    this.i = this.i + 1; this.i<256;
  }
  
  display() {
    //display walker
    stroke(0);
    fill(this.i, 0, 0);
    textSize(50);
	ellipse(this.x, this.y, random(1,30), random(1,30));
	// stroke(random(1,255), random(1,255), random(1,255));
	// line(200, 0, this.x, this.y);
    }
  • 서서히 색이 변할 수 있도록 해보았다.
  • this.i 라는 변수를 추가해주고, i++될 수 있게 값을 만들어주었다.

궁금한 점

  • 절차 지향과 객체 지향의 차이가 무엇인가?

JavaScript의 OOP

  • JavaScript는 여러 회사에서 구현하고 있다. ES6 (ECMAScript 2015) 버전.
  • Prototype-based OOP이다. Class-based OOP가 아니다.
  • Class는 아니지만 눈에 보이는 것은 Class처럼.
  • 자바스크립트 관련 참고 사이트 https://babeljs.io/docs/en/learn
  • 객체 지향은 속성 + 행동
  • 강아지를 예로 들면 강아지를 Class로 만들고
    • 속성 : 종, 털 색깔, 다리 갯수 등
    • 행동 : 달리기, 짓기 등

느낀 점

 코딩보다 원리나 구조, 문맥을 파악하는 것이 너무 어렵다. 이해를 하기가 힘들다. 기초 공부가 필요하다.

댓글