physics.js의 공식 튜토리얼을 따라하면서, 물리엔진 라이브러리를 알아보자!
<canvas id="viewport" width="500" height="500"></canvas>
물리 엔진의 경우 js에서 설정한다.
el
의 경우 canvas태그의 id값
을 넣어주면 된다.world.add
를 사용해 랜더러를 world
에 적용해준다.Physics(function(world){
const renderer = Physics.renderer('canvas', {
el: 'viewport',
width: 500,
height: 500
})
world.add(renderer);
...
})
Physics.body('사물유형', { 옵션 })
을 사용해 사물객체를 생성한다.world.add
를 사용해 world
에 추가한다. ...
const square1 = Physics.body('rectangle', {
x: 250, //x 위치
y: 250, //y축 위치
width: 50,
height: 50
});
const square2 = Physics.body('rectangle', {
x: 280,
y: 350,
width: 50,
height: 50
});
world.add(square1); //추가
world.add(square2);
utils.ticker
를 사용하여 애니메이션 루프를 진행시킨다.ticker.start()
를 실행하여 애니메이션 루프를 실행시킨다. (b)//4. 시뮬레이션 돌리기(실행시키기)
Physics.util.ticker.on(function(time, dt) {
world.step(time); //(a)
})
Physics.util.ticker.start(); //(b)
world.on('step', function() {
world.render(); //(c)
})
Physics.behavior(동작)
을 사용해 world에 물리 법칙(?)을 추가한다.constant-acceleration
는 중력을 의미한다. (a)body-impulse-response
를 지정하면 충돌에 반응할 수 있게 된다. (b)body-collision-detection
은 객체끼리 충돌이 발생하게 한다. (c)sweep-prune
을 지정하여 광범위한 위상 충돌을 감지할 수 있다. (d)//5. 동작 추가하기 (중력)
world.add(Physics.behavior('constant-acceleration') ); //(a)
world.add(Physics.behavior('body-impulse-response')); //(b)
world.add( Physics.behavior('body-collision-detection') ); //(c)
world.add( Physics.behavior('sweep-prune') ); //(d)
Physics.aabb(minX , minY , maxX , maxY)
을 사용해 경계를 만들어준다. (a)aabb: bound
를 하여 경계(aabb
)에 충돌시 탄성(bound
)를 준다. (b)restitution
은 복원성으로 원래대로 돌아가는 정도를 설정할 수 있다. (c) const bounds = Physics.aabb(0, 0, 500, 500); //(a)
world.add(Physics.behavior('edge-collision-detection', {
aabb: bounds, //(b)
restitution: 0.3 //(c)
}) );
Physics(function (world) {
const renderer = Physics.renderer("canvas", {
el: "viewport",
width: 500,
height: 500,
});
world.add(renderer);
const square1 = Physics.body("rectangle", {
x: 250,
y: 250,
width: 50,
height: 50,
});
const square2 = Physics.body("rectangle", {
x: 280,
y: 350,
width: 50,
height: 50,
});
world.add(square1);
world.add(square2);
Physics.util.ticker.on(function (time, dt) {
world.step(time);
});
Physics.util.ticker.start(); //동작 시키기
world.on("step", function () {
world.render(); //매 프레임마다 뷰를 새로 고치도록 함
});
world.add(Physics.behavior("constant-acceleration"));
world.add(Physics.behavior("body-impulse-response"));
world.add(Physics.behavior("body-collision-detection")); //몸체끼리 충돌발생
world.add(Physics.behavior("sweep-prune")); //광범위한 위상 충돌 감지
const bounds = Physics.aabb(0, 0, 500, 500);
world.add(
Physics.behavior("edge-collision-detection", {
aabb: bounds, //충돌시 탄성 주기
restitution: 0.3, //복원성(원래대로 돌아가는 정도)
})
);
});