忍者ブログ

Memeplexes

プログラミング、3DCGとその他いろいろについて

Planck.jsサンプルコード 力を加えて動かす

Planck.jsのサンプルコードを書きました。ブロックに力を加えて動かします。


サンプルコード

<canvas id="canvas" width="400" height="400" style="border:solid"></canvas>
<button id="forceButton">→</button>

<script src="planck.js"></script>

<script>

var World = planck.World,
	Vec2 = planck.Vec2,
	Edge = planck.Edge,
	Box = planck.Box;


class Demo{
	constructor(){
		this.world = this._createWorld();
		this._initializeGround(this.world);
		this._initializeBox(this.world);

		forceButton.onclick = () => {
			this.box.applyForceToCenter(Vec2(2000000, 0), true);
		};
	}

	_createWorld(){
		var world = World();
		world.setGravity(Vec2(0, -100));
		return world;
	}

	_initializeGround(world){
		var ground = world.createBody();
		ground.createFixture(Edge(Vec2(0, 0), Vec2(400, 0)));
	}

	_initializeBox(world){
		this.box = world.createBody().setDynamic();
		this.box.setPosition(Vec2(200, 300));

		this.boxShape = Box(10, 40);
		this.box.createFixture(this.boxShape);
		this.box.setMassData(this._getMassData(this.boxShape));
	}

	_getMassData(boxShape){
		var massData = {center:Vec2()};
		boxShape.computeMass(massData, 1);
		return massData;
	}

	run(){
		window.requestAnimationFrame(() => this.run());
		this._update();
		this._draw();
	}

	_update(){
		this.world.step(1 / 60);
	}

	_draw(){
		var context = canvas.getContext("2d");
		context.clearRect(0, 0, canvas.width, canvas.height);
		this._drawBox(context);
	}

	_drawBox(context){
		for(var fixture = this.box.getFixtureList(); fixture; fixture = fixture.getNext()){
			context.beginPath();

			for(var vertex of fixture.getShape().m_vertices){
				var transformedPosition = planck.Transform.mul(this.box.getTransform(), vertex);
				context.lineTo(transformedPosition.x, canvas.height - transformedPosition.y);
			}

			context.fill();
		}
	}
}


function main(){
	var demo = new Demo();
	demo.run();
}

main();

</script>

実行結果

解説

このプログラムは、[→]ボタンを押すとブロックに力が加わり、動きます。現実世界でこんな細長いブロックに力を加えたら微妙に傾いてしまうかもしれませんが、このシミュレーションでは傾きません。ちょうど重心に力をかけているからです。

物をさわったとき傾いてしまうのは、力が重心を通っていないからです。逆に言うと、回転させようと思ったら、重心から離れるほどよいのです。シーソーで外側に乗ったほうが、シーソーの傾きをうまくコントロールできるのと同じです。今回は、シーソーの真ん中に座ったのと同じ状態で、力はかかっているのですがその力が回転に使われないのです。

拍手[1回]

PR