01.Box2dWeb入門教程
阿新 • • 發佈:2019-01-30
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;
//1.建立一個世界
var world = new b2World(new b2Vec2(0,9.8),true);
//2.建立一個矩形剛體
//定義一個材質
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;//密度
fixDef.friction = 0.5;//摩擦
fixDef.restitution = 0.2;//彈性
fixDef.shape = new b2PolygonShape;//矩形
fixDef.shape.SetAsBox(5, 0.5);//寬高
//建立一個矩形地板剛體
var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_staticBody;//靜態的
bodyDef.position.x = 10; //X軸
bodyDef.position.y = 13; //Y軸
//世界中新增一個剛體
world.CreateBody(bodyDef).CreateFixture(fixDef);
//3.同上建立一個圓形剛體
var fixDef2 = new b2FixtureDef;
fixDef2.density = 1.0;
fixDef2.friction = 0.5;
fixDef2.restitution = 0.2;
fixDef2.shape = new b2CircleShape(1);
var bodyDef2 = new b2BodyDef;
bodyDef2.type = b2Body.b2_dynamicBody;
bodyDef2.position.x = 9;
bodyDef2.position.y = 1;
world.CreateBody(bodyDef2).CreateFixture(fixDef2);
//4.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);
//5.一幀幀執行
window.setInterval(update, 1000 / 60);
function update() {
//Take a time step.
world.Step(
1 / 60 //frame-rate
, 10 //velocity iterations
, 10 //position iterations
);
//Call this to draw shapes and other debug draw data.
world.DrawDebugData();
//Call this after you are done with time steps to clear the forces. You normally call this after each call to Step, unless you are performing sub-steps.
world.ClearForces();
//console.log(111);
};
}