1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

物理剛体シミュレーションを実行せよ。

サンプルコード


IO.puts """
<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/box2dweb@2.1.0-b/box2d.min.js"></script>
  </head>
  <body>
    <canvas id="c"></canvas>
    <script>
var b2Vec2 = Box2D.Common.Math.b2Vec2,
	b2BodyDef = Box2D.Dynamics.b2BodyDef,
	b2Body = Box2D.Dynamics.b2Body,
	b2FixtureDef = Box2D.Dynamics.b2FixtureDef,
	b2Fixture = Box2D.Dynamics.b2Fixture,
	b2DistanceJointDef = Box2D.Dynamics.Joints.b2DistanceJointDef,
	b2RevoluteJointDef = Box2D.Dynamics.Joints.b2RevoluteJointDef,
	b2World = Box2D.Dynamics.b2World,
	b2MassData = Box2D.Collision.Shapes.b2MassData,
	b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape,
	b2CircleShape = Box2D.Collision.Shapes.b2CircleShape,
	b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var canvas = document.getElementById("c");
canvas.width = 440;
canvas.height = 440;
var world = new b2World(new b2Vec2(0, 10), true);
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(canvas.getContext("2d"));
debugDraw.SetDrawScale(150);
debugDraw.SetFillAlpha(0.9);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
function createWall(x, y, w, h) {
	bodyDef.type = b2Body.b2_staticBody;
	bodyDef.position.x = x + w / 2;
	bodyDef.position.y = y + h / 2;
	fixDef.shape = new Box2D.Collision.Shapes.b2PolygonShape;
	fixDef.shape.SetAsBox(w / 2, h / 2);
	world.CreateBody(bodyDef).CreateFixture(fixDef);
}
function loop() {
	world.Step(1 / 60, 10, 10);
	world.DrawDebugData();
	world.ClearForces();
	setTimeout(loop, 15);
}
"""
IO.puts """
var bodyDef = new Box2D.Dynamics.b2BodyDef;
bodyDef.linearDamping = 0.1;
var fixDef = new Box2D.Dynamics.b2FixtureDef;
fixDef.restitution = 1;
createWall(0, 0, 2, 0.1);
createWall(0, 0, 0.1, 2);
createWall(2, 0, 0.1, 2);
createWall(0, 2, 2.1, 0.1);
fixDef.shape = new b2CircleShape(0.1);
fixDef.density = 0.4;
fixDef.friction = 0.9;
fixDef.restitution = 0.9;
bodyDef.type = b2Body.b2_dynamicBody;
bodyDef.position = new b2Vec2(1.5, 1.0);
bodyDef.linearVelocity = new b2Vec2(-5.0, -5.0);
world.CreateBody(bodyDef).CreateFixture(fixDef);
"""
IO.puts """
loop();
    </script>
  </body>
</html>
"""




成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?