概要
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>
"""
成果物
以上。