忍者ブログ

Memeplexes

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

Planck.jsサンプルコード 重力で落ちる円

JavaScriptで動く2次元の物理エンジン、Planck.jsを使ってみます。


Planck.js

Planck.jsは2次元のJavaScript用物理エンジンです。丸や四角のブロックが物理法則に従ってうごいて楽しそうです。ブログに載せるゲームを作るのにちょうどいいかもしれません。使い方をメモします。

使い方

ファイルはここで手に入ります:

GitHub - shakiba/planck.js: 2D JavaScript Physics Engine

このdistフォルダにあるplanck.jsを自分で書くプログラムのあるフォルダにコピーします。

サンプルコード

<canvas id="canvas" width="400" height="400"></canvas>

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

<script>

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


class Demo{
	constructor(){
		this.world = World();
		this.world.setGravity(Vec2(0, -100));

		var bar = this.world.createBody();
		bar.createFixture(Edge(Vec2(0, 0), Vec2(400, 0)));

		this.circle = this.world.createBody().setDynamic();
		this.circle.createFixture(Circle(30));
		this.circle.setPosition(Vec2(200, 400));
	}

	run(){
		window.requestAnimationFrame(() => this.run());
		this.world.step(1 / 60);
		this.draw();
	}

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

	drawCircle(context){
		for(var fixture = this.circle.getFixtureList(); fixture; fixture = fixture.getNext()){
			var position = this.circle.getPosition();
			var radius = fixture.getShape().getRadius();
			this.fillCircle(context, position.x, canvas.height - position.y, radius);
		}
	}

	fillCircle(context, x, y, radius){
		context.beginPath();
		context.ellipse(x, y, radius, radius, 0, 0, 2 * Math.PI);
		context.fill();
	}
}


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

main();

</script>

結果

解説

このプログラムは黒い丸が地面に落ちるシミュレーションです。

重力に(0, -100)(つまり、下向きに100)をセットし、幅400の地面をくわえ、半径30の円を空中の位置(200, 400)にセットしています。そしてパラパラ漫画のように、1/60秒ごとに少しずつ位置を変化させ、動いているように見せているのです。そうすると、空中にある円が落ちて地面の上で止まる様子がシミュレートされます。

拍手[0回]

PR