Learning
레슨 2 / 8·20분

바디와 제약

Body 옵션과 물리 속성

Matter.js의 모든 Body는 질량, 마찰, 탄성 등 물리 속성을 가집니다. Constraint(제약)은 두 바디를 연결하여 줄, 스프링, 관절 같은 구조를 만듭니다. Composite는 여러 바디와 제약을 하나의 그룹으로 묶어 관리합니다.

javascript
const { Bodies, World, Constraint, Composite } = Matter;

// ── Body 물리 옵션 상세 ──
const heavyBall = Bodies.circle(200, 100, 40, {
  restitution: 0.9,  // 탄성 계수 (0: 흡수, 1: 완전 반동)
  friction: 0.05,    // 표면 마찰 (0: 빙판, 1: 거친 표면)
  frictionAir: 0.01, // 공기 저항 (클수록 빨리 감속)
  density: 0.005,    // 밀도 → 질량에 영향 (높을수록 무거움)
  render: {
    fillStyle: '#f39c12',
    strokeStyle: '#e67e22',
    lineWidth: 2,
  },
});

// isStatic: true → 고정 객체 (바닥, 벽, 피벗)
const pivot = Bodies.circle(400, 100, 10, {
  isStatic: true,
  render: { fillStyle: '#ecf0f1' },
});

Constraint — 바디 연결하기

javascript
// ── 진자(Pendulum) 만들기 ──
const pendulumBob = Bodies.circle(500, 300, 25, {
  density: 0.004,
  render: { fillStyle: '#e74c3c' },
});

// Constraint로 피벗과 추를 연결 (줄)
const pendulumString = Constraint.create({
  bodyA: pivot,          // 연결 바디 A (고정점)
  bodyB: pendulumBob,    // 연결 바디 B (추)
  length: 200,           // 줄 길이
  stiffness: 1,          // 강성 (1: 단단한 막대, 0에 가까울수록 느슨)
  damping: 0,            // 감쇄 (0: 없음, 1: 최대 감쇄)
  render: {
    strokeStyle: '#bdc3c7',
    lineWidth: 2,
  },
});

// ── 스프링(Spring) 만들기 ──
const boxA = Bodies.rectangle(300, 200, 50, 50);
const boxB = Bodies.rectangle(500, 200, 50, 50);

const spring = Constraint.create({
  bodyA: boxA,
  bodyB: boxB,
  stiffness: 0.01,  // 낮은 강성 = 스프링처럼 늘어남
  damping: 0.05,    // 약간의 감쇄
  render: { strokeStyle: '#2ecc71' },
});

// ── Composite로 그룹 관리 ──
const pendulumGroup = Composite.create();
Composite.add(pendulumGroup, [pivot, pendulumBob, pendulumString]);

World.add(engine.world, [pendulumGroup, boxA, boxB, spring]);
  • restitution — 충돌 반발 계수 (0: 에너지 흡수, 1: 완전 반동)
  • friction — 접촉 시 표면 마찰력 (0~1)
  • frictionAir — 공기 저항으로 인한 감속 (0~1)
  • density — 밀도, 면적 x 밀도 = 질량
  • Constraint.stiffness — 연결 강성 (1: 막대, 0.01: 스프링)
  • Constraint.damping — 진동 감쇄 (1에 가까울수록 빨리 멈춤)
  • Composite — 바디와 제약을 그룹으로 묶어 한꺼번에 관리
💡

stiffness를 1로 설정하면 강체 연결(rigid), 0.01~0.1 범위로 설정하면 탄성이 있는 스프링 연결이 됩니다. 줄을 흔들리게 하고 싶다면 stiffness를 약간 낮추고 damping을 0에 가깝게 설정하세요.