技術解説
Matter.jsを使った物理シミュレーション入門
Matter.jsを使った物理シミュレーションの実装方法を、実際のコード例とともに解説します。
約1200文字
TypeScriptMatter.js物理シミュレーションプログラミング
Matter.jsを使った物理シミュレーション入門
物理シミュレーションを実装したいが、どこから始めればいいか分からない...この記事では、Matter.jsを使った物理シミュレーションの実装方法を、実際のコード例とともに解説します。
Matter.jsとは
Matter.jsは、JavaScriptで2D物理シミュレーションを実装するための軽量なライブラリです。重力、衝突検出、ばね、制約などの物理現象を簡単に実装できます。
主な特徴
- 軽量: 約100KB(圧縮後)
- 高性能: 60FPSを維持可能
- 柔軟性: カスタマイズ可能な物理パラメータ
- TypeScript対応: 型定義が提供されている
基本的な実装
エンジンの初期化
import Matter from 'matter-js';
// 物理エンジンの作成
const engine = Matter.Engine.create();
const world = engine.world;
// 重力の設定
world.gravity.x = 0;
world.gravity.y = 1;
world.gravity.scale = 0.001;
物理ボディの作成
// 矩形ボディの作成
const box = Matter.Bodies.rectangle(400, 200, 80, 80, {
mass: 1,
friction: 0.1,
restitution: 0.3, // 反発係数
});
// 円形ボディの作成
const circle = Matter.Bodies.circle(400, 100, 30, {
mass: 0.5,
friction: 0.05,
});
// ワールドに追加
Matter.World.add(world, [box, circle]);
エンジンの実行
// レンダラーの作成(オプション)
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 600,
},
});
// レンダラーの実行
Matter.Render.run(render);
// エンジンの実行
const runner = Matter.Runner.create();
Matter.Runner.run(runner, engine);
応用的な実装
ばねの実装
// 2つのボディをばねで接続
const constraint = Matter.Constraint.create({
bodyA: box,
bodyB: circle,
stiffness: 0.5, // 剛性
damping: 0.05, // 減衰
length: 100, // 自然長
});
Matter.World.add(world, constraint);
マウスインタラクション
// マウス制約の作成
const mouse = Matter.Mouse.create(render.canvas);
const mouseConstraint = Matter.MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false,
},
},
});
Matter.World.add(world, mouseConstraint);
パフォーマンス最適化
反復回数の調整
// エンジンの反復回数を調整
const engineAny = engine as any;
engineAny.positionIterations = 6; // 位置の反復回数
engineAny.velocityIterations = 4; // 速度の反復回数
engineAny.constraintIterations = 2; // 制約の反復回数
スリープモードの有効化
// 動いていないボディをスリープ状態にする
engine.enableSleeping = true;
まとめ
Matter.jsを使うことで、簡単に物理シミュレーションを実装できます。基本的な実装から始めて、徐々に応用的な機能を追加していくことで、より高度な物理シミュレーションを作成できます。
関連ツール
この記事で解説した内容を実際に試せるツールを用意しています。ぜひ使ってみてください。
関連ツール
関連記事
技術解説
TypeScriptで物理シミュレーションを実装する方法
TypeScriptを使って物理シミュレーションを実装する方法を、実際のコード例とともに詳しく解説します。
TypeScript物理シミュレーションMatter.js+2
2026年1月8日
技術解説
Canvas APIを使った描画の最適化
Canvas APIを使った描画を最適化する方法を、実際のコード例とともに詳しく解説します。
Canvas APIパフォーマンス最適化+2
2026年1月8日
技術解説
Next.js App Routerでの実装パターン
Next.js App Routerを使った実装パターンを、実際のコード例とともに詳しく解説します。
Next.jsApp RouterReact+2
2026年1月8日