오늘은 질량이 1이 아닌 동그라미가 중력과 바람과 바닥과 벽에 반응하는 프로그램을 만들어 보겠습니다. 질량이 1인 경우, 우리는 Acceleration = Net Force 로 계산을 하였지요? 질량이 1이 아닌 경우에선, 힘을 질량으로 나누어 가속도를 구할 수 있을 것 같네요. Force = Acceleration * Mass 에서 Acceleration = Force / Mass 를 이끌어 낼 수 있으니까요^^*
이렇게 힘을 질량으로 나누어 얻은 값을 받는 변수를 하나 만들고, 그 변수를 가속도에 더하도록 할게요. 벡터와 벡터 사이의 연산을 다루기 때문에 static 변수를 사용해 보겠습니다.
아래 동영상을 4:54까지 보시면 되어요~
class Mover{
constructor(x,y){
this.pos = createVector(x,y);
this.vel = createVector(0,0);
this.acc = createVector(0,0);
this.r = 16;
this.mass = 2;
//동그라미의 질량을 2로 설정해 봅시다.
}
applyForce(force){
let f = p5.Vector.div(force, this.mass);
//힘을 질량으로 나눈 값을 변수 f에 저장한다.
this.acc.add(f);
//가속도에 f를 더한다.
}
edges(){
if(this.pos.y >= height - this.r){
this.pos.y = height - this.r;
this.vel.y *= -1;
}
if(this.pos.x >= width - this.r){
this.pos.x = width - this.r;
this.vel.x *= -1;
} else if(this.pos.x <= this.r){
this.pos.x = this.r;
this.vel.x *= -1;
}
}
update(){
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.set(0,0);
}
show(){
stroke(255);
strokeWeight(2);
fill(255, 100);
ellipse(this.pos.x, this.pos.y, this.r*2);
}
}
let moverA;
let moverB;
function setup() {
createCanvas(400, 400);
moverA = new Mover(100,200);
moverB = new Mover(300,200);
}
function draw() {
background(0);
if(mouseIsPressed){
let wind = createVector(0.1, 0);
moverA.applyForce(wind);
moverB.applyForce(wind);
}
let gravity = createVector(0,0.2);
moverA.applyForce(gravity);
moverA.update();
moverA.edges();
moverA.show();
moverB.applyForce(gravity);
moverB.update();
moverB.edges();
moverB.show();
}
이것을 클릭하여 mover.js 파일과 sketch.js 파일을 열어 코드를 살펴 보세요. 삼각형 프로그램 실행, 사각형 종료~^^*
내일은 서로 다른 질량의 동그라미에 대한 프로그램을 만들어 볼게요. 음….이 순간, 갈릴레오 갈릴레이가 떠오르시는 분, 손~^^* 네, 피사의 사탑 실험을 오늘 한 번 살펴 보면, 내일 프로그램이 좀더 편안하게 다가올 것 같아요. 낙하실험도 살펴보고, 피사의 사탑도 직접 들어가 봅시다~^^* 갈릴레오 갈릴레이가 못다 이루신 꿈이 있다면, 앞으로 우리가 이어서 실현시켜 보아요. 꿈은 이루어 집니다!!
내일 또 만나요~^^*
댓글 남기기