[PR]
×
[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
プログラミング、3DCGとその他いろいろについて
[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
JavaScriptで動く2次元の物理エンジン、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秒ごとに少しずつ位置を変化させ、動いているように見せているのです。そうすると、空中にある円が落ちて地面の上で止まる様子がシミュレートされます。