물리 엔진은 게임과 시뮬레이션에서 물리 법칙(중력, 충돌, 마찰)을 실시간으로 시뮬레이션하는 소프트웨어다. 강체 역학, 충돌 감지, 제약 조건 해결을 수치 적분으로 구현한다.
핵심 개념
강체 역학 (Rigid Body Dynamics):
- 위치: x(t)
- 속도: v(t) = dx/dt
- 힘과 가속도: F = ma → a = F/m
- 회전: 토크, 각속도, 관성 모멘트
충돌 감지 (Collision Detection):
- Broad Phase: AABB로 후보 쌍 빠르게 추출
- Narrow Phase: GJK/SAT로 정확한 충돌 판정
- Continuous CD: 빠른 물체의 터널링 방지
수치 적분 (Numerical Integration):
- Euler: 간단하지만 에너지 발산 가능
- Verlet: 속도 제거, 에너지 보존 우수
- RK4: 정확하지만 계산 비용 높음
간단한 2D 물리 시뮬레이션
typescript
interface Vec2 { x: number; y: number; }
class RigidBody {
position: Vec2;
velocity: Vec2;
acceleration: Vec2 = { x: 0, y: 0 };
mass: number;
restitution: number = 0.8; // 탄성 계수
constructor(x: number, y: number, mass: number) {
this.position = { x, y };
this.velocity = { x: 0, y: 0 };
this.mass = mass;
}
applyForce(fx: number, fy: number): void {
this.acceleration.x += fx / this.mass;
this.acceleration.y += fy / this.mass;
}
// Symplectic Euler 적분
integrate(dt: number): void {
// 중력 적용
this.applyForce(0, 9.81 * this.mass);
this.velocity.x += this.acceleration.x * dt;
this.velocity.y += this.acceleration.y * dt;
this.position.x += this.velocity.x * dt;
this.position.y += this.velocity.y * dt;
// 가속도 리셋
this.acceleration = { x: 0, y: 0 };
}
}
// 바닥 충돌 처리
function resolveFloorCollision(body: RigidBody, floorY: number): void {
if (body.position.y > floorY) {
body.position.y = floorY;
body.velocity.y = -body.velocity.y * body.restitution;
body.velocity.x *= 0.95; // 마찰
}
}
주요 물리 엔진
| 엔진 | 특징 | 사용처 |
|---|
| Box2D | 2D, C++/JavaScript 바인딩 | 2D 게임 (Angry Birds) |
| Bullet | 3D, 오픈소스 | Unity, Blender |
| PhysX | NVIDIA, GPU 가속 | Unreal Engine |
| Rapier | Rust, 웹어셈블리 지원 | 웹 게임, Bevy |
| Matter.js | JavaScript 2D | 웹 게임 프로토타입 |
관련 문서