忍者ブログ

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,
	Transform = planck.Transform;


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

		forceButton.onclick = () => {
			this.box.applyForce(Vec2(2000000, 0), this.forcePosition, 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);
		this.forcePosition = Transform.mul(this.box.getTransform(), Vec2(0, 10));
	}

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

		context.fillStyle = "green";
		context.fillRect(this.forcePosition.x - 5, canvas.height - (this.forcePosition.y) - 5, 10, 10);
	}

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

			for(var vertex of fixture.getShape().m_vertices){
				var transformedPosition = 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