box2d in JavaScript use the Daquan record

Source: Internet
Author: User

Index.html page

<?php?><! doctype html>

Box2d.js page

var world;var scale = 30;//30 pixels on canvas represents 1 meters in the world of Box2D Function init ()  {  &NBSP;&NBSP;&NBSP;VAR&NBSP;GRAVITY&NBSP;=&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (0,9.8);//indicates that the acceleration of gravity is 9.8m/s squared, Direction down     var allowsleep = true;//allow stationary objects to hibernate, dormant objects do not participate in physical simulation calculations      world = new box2d.dynamics.b2world (Gravity,allowsleep);     Createfloor ();     //create some objects with simple shapes     createrectangularbody ();     createcircularbody ();     createsimplepolygonbody ();     createcomplexbody ();     createresolutejoint ();     Createspecialbody ();     listenforcontact ();     setupdebugdraw ();     animate ();} Function drawspecialbody ()  {    var positon =  Specialbody.getposition ();  &nbSp;  var angle = specialbody.getangle ()     //Moving and rotating objects      context.translate (Positon.x*scale,positon.y*scale);     context.rotate (angle);     //drawing solid round faces     context.fillStyle =  rgb (200,150,250);     context.beginpath ();     context.arc (0,0,30,0,2*Math.PI,false);     context.fill ();     //draw two rectangles of eyes      context.fillstyle =  "RGB (255,255,255);";     context.fillrect ( -15,-15,10,5);     context.fillrect (5,-15,10,5);     //draws an arc up or down, depending on the life value of the Smile     context.strokeStyle =  "RGB ( 255,255,255); ";     context.beginpath ();     if (Specialbody.getuserdata () .life  > 100) {        context.arc (0,0,10, math.pi,2*math.pi,true);    }else{         Context.arc (0,10,10,math.pi,2*math.pi,false);     }    context.stroke () ;     context.rotate (-angle);     context.translate (-positon.x*scale,- Positon.y*scale);} Var specialbody;function createspecialbody ()  {    var bodydef =  new box2d.dynamics.b2bodydef ();    bodydef.type =  box2d.dynamics.b2body.b2_dynamicbody;    bodydef.position.x = 450/scale;     bodydef.position.y = 0/scale;    specialbody = world . Createbody (bodydef);     specialbody.setuserdata ({name: "Special", life:250});//Set Object custom properties     var fixturedef = new box2d.dynamics.b2fixturedef ();     fixturedef.density = 1.0;    fixturedef.friction = 0.5;     fixturedef.restitution = 0.5;    fixturedef.shape = new  Box2D.Collision.Shapes.b2CircleShape (30/scale);    var fixture =  Specialbody.createfixture (fixturedef);} Function listenforcontact ()  {    /*      box2d.dynamics.b2contactlistener  Object Method     begincontact (): Two objects are called when they begin to contact      endcontact (): Two objects are called at end of Contact     postsolve (): Called when the solver is complete, useful for collision detection      presolve (): Call      */    var listener = before Solver solves  new box2d.dynamics.b2contactlistener;    listener. Postsolve = function (contact,impulse) {        var body1  = contact. Getfixturea (). GetBody ();          var body2 = contact. Getfixtureb (). GetBody ();         if (body1 == specialbody | |  body2 == specialbody) {             var impulsealongnormal = impulse.normalimpulses[0];             specialbody.getuserdata () .life -= impulsealongnormal;             console.log ("The special body was  in a collision with impulse ", Impulsealongnormal," And its life has  now become ",             Specialbody.getuserdata (). Life);        }    };     world. Setcontactlistener (listener);} Create rotational Joint FUNction createresolutejoint ()  {    //define the first object     var  Bodydef1 = new box2d.dynamics.b2bodydef ();    bodydef1.type =  box2d.dynamics.b2body.b2_dynamicbody;    bodydef1.position.x = 480/scale;     bodyDef1.position.y = 50/scale;    var body1 =  World. Createbody (BODYDEF1);    var fixturedef1 = new  Box2D.Dynamics.b2FixtureDef ();    fixturedef1.density = 1.0;     fixtureDef1.friction = 0.5;    fixtureDef1.restitution = 0.5;     fixturedef1.shape = new box2d.collision.shapes.b2polygonshape ();     fixturedef1.shape.setasbox (50/scale,10/scale);     body1. Createfixture (FIXTUREDEF1);     var&nbSp;bodydef2 = new box2d.dynamics.b2bodydef ();    bodydef2.type =  box2d.dynamics.b2body.b2_dynamicbody;    bodydef2.position.x = 470/scale;     bodyDef2.position.y = 50/scale;    var body2 =  World. Createbody (BODYDEF2);     //creates a second carrier and adds a polygon shape to the object     var fixturedef2  = new box2d.dynamics.b2fixturedef ();    fixturedef2.density =  1.0;    fixturedef2.friction = 0.5;     fixturedef2.restitution = 0.5;    fixturedef2.shape = new  Box2D.Collision.Shapes.b2PolygonShape ();    var points = [   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (0,0),         new box2d.common.math.B2VEC2 (40/scale,50/scale), &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (50 /scale,100/scale), &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 ( -50/scale, 100/scale), &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 ( -40/scale,50/ Scale)     ];    fixturedef2.shape.setasarray (points,points.length);     body2. Createfixture (FIXTUREDEF2);     //creating junction connections Body1 and body2    var  Jointdef = new box2d.dynamics.joints.b2revolutejointdef ();    var  JOINTCENTER&NBSP;=&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (470/scale,50/scale);     Jointdef.initialize (body1,body2,jointcenter);//point to access and access point     world. Createjoint (jointdef);//Create an Access point   join the World}//Create an object consisting of two objects function createcomplexbody ()  {     var bodydef&nbsP;= new box2d.dynamics.b2bodydef ();    bodydef.type =  box2d.dynamics.b2body.b2_dynamicbody;    bodydef.position.x = 350/scale;     bodyDef.position.y = 50/scale;    var body =  World. Createbody (bodydef);    var fixturedef = new  Box2D.Dynamics.b2FixtureDef ();    fixturedef.density = 1.0;     fixtureDef.friction = 0.5;    fixtureDef.restitution = 0.7;     fixturedef.shape = new box2d.collision.shapes.b2circleshape (40/scale);     body. Createfixture (fixturedef);    fixturedef.shape = new  Box2D.Collision.Shapes.b2PolygonShape ();    var points = [       new box2d.common.math.b2vec2 (0,0), &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (40/scale,50/scale), &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 (50/scale,100/scale),  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 ( -50/scale,100/scale),   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;NEW&NBSP;BOX2D.COMMON.MATH.B2VEC2 ( -40/scale,50/scale)      ];    fixturedef.shape.setasarray (points,points.length);     body . Createfixture (fixturedef);} Function createsimplepolygonbody ()  {    var bodyDef = new  Box2D.Dynamics.b2BodyDef ();     bodydef.type = box2d.dynamics.b2body.b2_ dynamicbody;    bodydef.position.x = 230/scale;     bodydef.position.y = 50/scale;    var fixturedef = new  Box2d.dynamics.B2fixturedef ();    fixturedef.density = 1;     fixturedef.friction = 0.5;    fixturedef.restitution = 0.2;     fixturedef.shape = new box2d.collision.shapes.b2polygonshape ();     var points = [        new  BOX2D.COMMON.MATH.B2VEC2 (0,0),        new  BOX2D.COMMON.MATH.B2VEC2 (40/scale,50/scale),        new  BOX2D.COMMON.MATH.B2VEC2 (50/scale,100/scale),        new  BOX2D.COMMON.MATH.B2VEC2 ( -50/scale,100/scale),        new  BOX2D.COMMON.MATH.B2VEC2 ( -40/scale,50/scale)     ];     FixtureDef.shape.SetAsArray (points,points.length);     var body = world.Createbody (bodydef);     var fixture = body. Createfixture (fixturedef);    /*     all coordinates are relative to the origin of the object. The first point (0,0) starts at the origin of the object, will be placed in the position of the object (230,50) .     no need to close the polygon, box2d will automatically do it for us .     all vertices must be defined in a clockwise direction      */}function createrectangularbody ()  {   var  Bodydef =new box2d.dynamics.b2bodydef ();    bodydef.type =  box2d.dynamics.b2body.b2_dynamicbody;    bodydef.position.x = 40 /  Scale;    bodydef.position.y = 100 / scale;    var  fixturedef = new box2d.dynamics.b2fixturedef ();     fixturedef.density  = 1;//density     fixturedef.friction = 0.5;//Friction coefficient      fixturedef.restitution = 0.8;//Elastic recovery coefficient    &nbSp;fixturedef.shape = new box2d.collision.shapes.b2polygonshape ();     FixtureDef.shape.SetAsBox (30/scale,50/scale);     var body = world. Createbody (bodydef);     var fixture = body. Createfixture (fixturedef);} Function createcircularbody ()  {    var bodyDef = new  Box2D.Dynamics.b2BodyDef ();     bodydef.type = box2d.dynamics.b2body.b2_ dynamicbody;    bodydef.position.x = 130/scale;     bodydef.position.y = 100/scale;    var fixturedef = new  Box2D.Dynamics.b2FixtureDef ();    fixturedef.density  = 1;     fixturedef.friction = 0.5;    fixturedef.restitution = 0.7 ;    fixturedef.shape = new Box2D.Collision.Shapes.b2CircleShape (30/scale);     var body = world. Createbody (bodydef);     var fixture = body. Createfixture (fixturedef);} var timestep = 1 / 60;//the number of iterations recommended by the BOX2D manual, the speed is 8, the position is 3var velocityiterations =  8;var positioniterations = 3;function animate ()  {    world. Step (timestep,velocityiterations,positioniterations);     world. Clearforces ();     world. Drawdebugdata ();     if (Specialbody && specialbody.getuserdata (). Life  <= 0) {        world. Destroybody (specialbody);//Remove objects from the world         specialBody =  Undefined;        console.log ("The special body was  destroyed ");     } &nbsP;  if (specialbody) {        drawspecialbody ();     }    settimeout (animate,timestep);} Function createfloor ()  {    var bodyDef = new  box2d.dynamics.b2bodydef;    bodydef.type = box2d.dynamics.b2body.b2_staticbody;     bodydef.position.x = 640/2/scale;    bodydef.position.y  = 450/scale;    //fixture used to add shape to body for collision detection     var  fixturedef = new box2d.dynamics.b2fixturedef;    fixturedef.density =  1.0;    fixtureDef.friction = 0.5;     fixturedef.restitution = 0.2;    fixturedef.shape = new  Box2d.collision.shapes.b2polygonshape;    fixturedef.shape.setasbox (320/scalE,10/scale);     var body = world. Createbody (bodydef);     var fixture = body. Createfixture (fixturedef);} Var context;function setupdebugdraw ()  {    context =  document.getElementById (' canvas '). GetContext (' 2d ');     var debugdraw = new  box2d.dynamics.b2debugdraw ();     //use the canvas drawing environment to draw the debug screen      Debugdraw.setsprite (context);     //set drawing scale     debugdraw.setdrawscale ( scale);     //fills with a transparency of 0.3    debugdraw.setfillalpha (0.3);   The width of the   //line is 1    debugdraw.setlinethickness (1.0);     // Draw all shape and joint    debugdraw.setflags (box2d.dynamics.b2debugdraw.e_shapebit |  Box2D.Dynamics.b2DebugDraw.e_jointBit);     //set the modulation drawing mode   &nbsP; world. Setdebugdraw (Debugdraw);}


box2d in JavaScript use the Daquan record

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.