JavaScript-mechanics-box2D
Материал из Department of Theoretical and Applied Mechanics
Версия от 16:29, 19 февраля 2014; Денис (обсуждение | вклад)
<addscript src=Box2dWeb-21a3min/>
Не удается найти HTML-файл box2D_example_TM.html
Текст программы на языке JavaScript, использованы библиотека Box2DJS, а также исходный код с сайта библиотеки. Для простоты js-скрипт интегрирован прямо в html файл: <toggledisplay status=hide showtext="Показать↓" hidetext="Скрыть↑" linkstyle="font-size:default"> Файл "box2D_example.html"
<html>
<head>
<title>Box2dWeb example</title>
</head>
<body onload="init();">
<canvas id="canvas" width="600" height="400"></canvas>
</body>
<script type="text/javascript" src="Box2dWeb-2.1.a.3.min.js"></script>
<script type="text/javascript">
var world;
function init() {
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2BodyDef = Box2D.Dynamics.b2BodyDef
, b2Body = Box2D.Dynamics.b2Body
, b2FixtureDef = Box2D.Dynamics.b2FixtureDef
, b2Fixture = Box2D.Dynamics.b2Fixture
, b2World = Box2D.Dynamics.b2World
, b2MassData = Box2D.Collision.Shapes.b2MassData
, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
, b2DebugDraw = Box2D.Dynamics.b2DebugDraw
;
world = new b2World(
new b2Vec2(0, 10) //gravity
, true //allow sleep
);
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new b2BodyDef;
//create ground
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.x = 10;
bodyDef.position.y = 13;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(10, 0.01);
world.CreateBody(bodyDef).CreateFixture(fixDef);
//create some objects
bodyDef.type = b2Body.b2_dynamicBody;
fixDef.shape = new b2PolygonShape; // добавим прямоугольник
fixDef.shape.SetAsBox(0.5, 2); // размеры прямоугольника
bodyDef.position.x = 10;
bodyDef.position.y = 10;
world.CreateBody(bodyDef).CreateFixture(fixDef);
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(2, 0.5);
bodyDef.position.x = 10;
bodyDef.position.y = 8;
world.CreateBody(bodyDef).CreateFixture(fixDef);
fixDef.shape = new b2CircleShape(2); // добавим круг
bodyDef.position.x = 13;
bodyDef.position.y = 3;
world.CreateBody(bodyDef).CreateFixture(fixDef);
//setup debug draw
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(30.0);
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update, 1000 / 60);
};
function update() {
world.Step(
1 / 60 //frame-rate
, 10 //velocity iterations
, 10 //position iterations
);
world.DrawDebugData();
world.ClearForces();
};
</script>
</html>
</toggledisplay>