物理エンジンは様々なケースで利用されています。ゲームはもちろんのこと、オブジェクトが動く際に、それがよりリアルに感じられるためには物理エンジンが欠かせません。複数のオブジェクトが関係し合う場合も同様です。 有名どころとしてはBox2dが知られていますが、今回はp2.jsを紹介します。Web上で動作するJavaScript製の物理エンジンです。

p2.jsの使い方

p2.jsは多数のデモを用意していますが、今回はその一部を紹介します。

二つくっついたオブジェクト同士が衝突するデモ。

一つの物質が横に飛んでいくもの。

多数のオブジェクトが衝突するデモ。

車のデモ。矢印キーで動かせます。

実際に車を動かしてみたところ。バネもあって、ショックを吸収しながら進んでいるのが分かります。

p2.jsは衝突検出、コンタクト、摩擦、反発、モーター、スプリングなどの機能が備わっています。サンプルコードは次のようになっていて、簡単な図形を定義しつつ、それらを別なオブジェクトに追加していくという形になっています。

// Create a physics world, where bodies and constraints live
var world = new p2.World({
    gravity:[0, -9.82]
});

// Create an empty dynamic body
var circleBody = new p2.Body({
    mass: 5,
    position: [0, 10]
});

// Add a circle shape to the body.
var circleShape = new p2.Circle({ radius: 1 });
circleBody.addShape(circleShape);

// ...and add the body to the world.
// If we don't add it to the world, it won't be simulated.
world.addBody(circleBody);

// Create an infinite ground plane.
var groundBody = new p2.Body({
    mass: 0 // Setting mass to 0 makes the body static
});
var groundShape = new p2.Plane();
groundBody.addShape(groundShape);
world.addBody(groundBody);

// To get the trajectories of the bodies,
// we must step the world forward in time.
// This is done using a fixed time step size.
var timeStep = 1 / 60; // seconds

// The "Game loop". Could be replaced by, for example, requestAnimationFrame.
setInterval(function(){

    // The step method moves the bodies forward in time.
    world.step(timeStep);

    // Print the circle position to console.
    // Could be replaced by a render call.
    console.log("Circle y position: " + circleBody.position[1]);

}, 1000 * timeStep);

p2.jsはHTML5/JavaScript製、MIT Licenseのオープンソース・ソフトウェアです。

schteppe.github.com Heightfield demo - p2.js physics engine schteppe/p2.js