忍者ブログ

Memeplexes

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

Planck.jsサンプルコード 地面にぶつかって回転する箱

Planck.jsのサンプルコードを書きました。箱を落として地面の上で倒します。


サンプルコード

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

<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);
	}

	_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.box.setAngle(Math.PI / 6);

		var boxShape = Box(10, 40);
		this.box.createFixture(boxShape);
		this.box.setMassData(this._getMassData(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>

結果

解説

このプログラムは傾いた箱を空中から地面に落とします。地面に当たった箱は倒れます。地面からの反作用により回転するのです。

拍手[0回]

PR