I have seen a lot of sample but didn't found the basic code of Box2d in Javascript. So i think i should put this in blog to help others.
This display is here
and code is
<script>
function init() {
var completeScaleRatio = 30;
var canvasWd = document.getElementById("canvas").width;
var canvasHt = document.getElementById("canvas").height;
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2AABB = Box2D.Collision.b2AABB
, 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
, b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef
;
var world = new b2World(
new b2Vec2(0, 10)
, true
);
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = .2;
var bodyDef = new b2BodyDef;
//create ground
bodyDef.type = b2Body.b2_staticBody;
fixDef.shape = new b2PolygonShape;
//Bottom
bodyDef.position.Set(10, canvasHt / completeScaleRatio-.1);
fixDef.shape.SetAsBox(20, .1);
world.CreateBody(bodyDef).CreateFixture(fixDef);
//Top
bodyDef.position.Set(10, .1);
world.CreateBody(bodyDef).CreateFixture(fixDef);
//Left
bodyDef.position.Set(.1, 0);
fixDef.shape.SetAsBox(.1, 14);
world.CreateBody(bodyDef).CreateFixture(fixDef);
//Right
bodyDef.position.Set(canvasWd/completeScaleRatio-.1, 0);
world.CreateBody(bodyDef).CreateFixture(fixDef);
//Create Bodies
bodyDef.type = b2Body.b2_dynamicBody;
var carShape = new b2PolygonShape();
var vertix = new Array(new b2Vec2(0, 0), new b2Vec2(.5, -2), new b2Vec2(1, 3), new b2Vec2(.7, 3), new b2Vec2(0, 1));
carShape.SetAsArray(vertix);
fixDef.shape = carShape
bodyDef.position.Set(5, canvasHt / completeScaleRatio/2);
world.CreateBody(bodyDef).CreateFixture(fixDef);
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(completeScaleRatio);
debugDraw.SetFillAlpha(1);
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 , 10, 10);//Gravity Animation is caused by this.
world.DrawDebugData(); // If removed then no bas Area will be shown
world.ClearForces();
}
</script>
No comments:
Post a Comment