Close Menu
Technotification
    Facebook X (Twitter) Instagram
    Facebook X (Twitter) Instagram
    Technotification
    • Home
    • News
    • How To
    • Explained
    • Facts
    • Lists
    • Programming
    • Security
    • Gaming
    Technotification
    Home › Programming › How to make 2D Physics Games with Box2D

    How to make 2D Physics Games with Box2D

    By Vikram Singh RaoJuly 30, 2020
    Facebook Twitter Reddit LinkedIn
    Create 2D Physics Games with Box2D

    Create 2D Physics Games with Box2D

    What makes games feel real is the physics in it. Angry Birds wouldn’t feel as good and definitely have achieved the level of popularity that it has, if there had been no physics in the game. The piggies rolling over, bumping into structures and bringing down entire wooden buildings feel so natural. This is made possible thanks to Physics engine. Mainstream games use much advanced APIs like PhysX and Havok. Browser based games use JavaScript libraries like box2web, Ammo.js, Cannon.js, JigLibJSetc. Box2D is open source 2D physics engine that has been used for implementing 2D game physics across a great many platforms. Some of the games built using the engine are Angry Birds, Happy Wheels, Tiny Wings, Crayon Physics Deluxe, Limbo etc. Box2D has been used on Nintendo DS, Wii, mobile OSes like Android, BB1O and iOS. It has also been ported to many languages and we are going to be looking at one such part – Box2dWeb, a JavaScript port of Box2D.

    Why Box2dWeb?

    Firstly, we are only working with 2-dimensional physics and Box2dWeb is only programmed to simulate physics in a 2-dimensional world. Its constraint system is called joints and it’s easy to set up and use. Even setting up collision detection is relatively simple since you just have to add a listener to that particular object. It is quite fast to execute and as with any programming language, only poor coding can mess that up. The API is very simple; you can always refer the original C/C++ manual or the manual for the Flash port if you find the JavaScript manual lacking. Overall, it’s a feature rich 2-dimensional physics that is supported on all major browsers.

    boxExamples Create 2D Physics Games with Box2D

    10 Create 2D Physics Games with Box2D

    Starting with Simple Scene:

    We’ll get the body tag out of the way first. It’s just the canvas within which the demo takes place.

    <body onload=”int();”>

    <canvas id=”canvas”width=”600” height=”400”></canvas>

    </body>

    Now, the very first thing that needs to be done is to set up a world in which all of the actions are to take place. To do this we need to create an instance of b2World which in turn requires you to declare a vector along which the force of gravity will act upon all objects (both free-falling and pivoted) within the canvas. Vectors are defined using the b2Vec2 function, which is a 2D column vector with two elements.

    var world = new b2World(

    new b2Vec2(0,10) //gravity

    , true

    );

     

    Create 2D Physics Games with Box2D 1
    Click on the image to download the file and preview it.

     

    After downloading the file you can view the source by pressing Ctrl + U.

    Once, this is done, we’ll add a ground surface. We create objects and define their state using b2BodyDef and then create fixtures using b2Fixtutre and define their physical properties like density, friction, restitution etc. using b2FixtureDef. An entire list of all parameters that can be used if available in the documentation.

      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 = 9;

    bodyDef.position.y = 13;

    fixDef.shape = new b2PolygonShape;

    fixDef.shape.SetAsBox(10, 0.5);

    world.CreateBody(bodyDef).CreateFixture(fixDef);

     

    make2D Physics Games with Box2D

    You can use the same definition to create walls and enclosures. Now we’ll add some objects that have random characteristics. We’re going to be adding ten objects and we’ll be randomizing their shape (quadrilaterals or circles). Further on, even the length/ width/ radius will be randomizing along with the co-ordinates where they are to be initialized.

    bodyDef.type = b2Body.b2_dynamicBody;

    for(var I = 0; I < 10; ++i)    { // creating 10 objects

    if(Math.random() > 0.5) { // randomizing shape using a condition

    fixDef.shape = new b2PolygonShape;

    fixDef.shape.SetAsBox(

    Math.random() + 0.1 // set width of box

    ,   Math.random() + 0.1 //set height of box

    );

    } else {

    fixDef.shape = newb2CircleShape(

    Math.random() + 0.1 //set radius of circle

    );

    }

    bodyDef.position.x = Math.random()

    *10; //initial position x-co-ordinate

    bodyDef.position.y = Math.random()

    *10; //initial position y-co-ordinate

    World.CreateBody(bodyDef).CreateFixture(fixDef);

    }

     

    An optional step is to setup debugdraw, which paints all the objects so you can observe interactions and subsequently debug. You can also mark out the object that is active and non-active using different colors.

     

    var debugDraw = new b2DebugDraw();

    debugDraw.SetSprite(document.getElementById(“canvas”).getContext(‘2d”));

    debugDraw.SetDrawScale(30.0);

    debugDraw.SetlineThickness(1.0);

    debugDraw.

    SetFlag(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);

    World.SetDebugDraw(debugDraw);

    window.setInterval(update, 1000 / 600);

    The last thing that needs to be done is to update the world whenever actions are performed. These can be user generated actions or actions resulting from incidental collisions of objections in the game world.

    function update() {

    world.Step(

    1/60 //frame-rate

    , 10    // velocity iterations

    , 10   // position iterations

    );

    world.DrawDebugData();

    world.ClearForces();

    };

     

    To summarize, we’ve created a world, implemented gravity along a vector. A ground surface was added as a rigid body and then ten random objects were generated that would drop down and collide with the ground. This is the simplest implementation of the JavaScript library and we’d love to see any works that you’ve created using the same library.

    As created by digit

    Resources:

    https://code.google.com/p/box2dweb/

    Box2D API Documentation

    https://box2d.org/manual.pdf

    Box2D Forum

    https://box2d.org/forum/

    Example Featured in this article

    https://pastebin.com/0a94fJRW

    More useful info at

    gamasutra 

    raywenderlich

     

    Share. Facebook Twitter LinkedIn Tumblr Reddit Telegram WhatsApp
    Vikram Singh Rao
    • Website
    • Facebook
    • X (Twitter)
    • LinkedIn

    I am an entrepreneur at heart who has made his hobby turned a passion, his profession now.

    Related Posts

    The Best Python Libraries for Data Visualization in 2025

    April 1, 2025

    Is C++ Still Relevant in 2025 and Beyond?

    February 20, 2025

    5 Best Programming Languages for Machine Learning in 2025

    February 18, 2025

    10 Must-Have Chrome Extensions for Web Developers in 2025

    February 17, 2025

    Difference Between C, C++, C#, and Objective-C Programming

    February 16, 2025

    How to Learn Programming Faster and Smarter in 2025

    February 14, 2025
    Lists You May Like

    10 Sites to Watch Free Korean Drama [2025 Edition]

    January 2, 2025

    10 Best RARBG Alternative Sites in April 2025 [Working Links]

    April 1, 2025

    The Pirate Bay Proxy List in 2025 [Updated List]

    January 2, 2025

    10 Best Torrent Search Engine Sites (2025 Edition)

    February 12, 2025

    10 Best GTA V Roleplay Servers in 2025 (Updated List)

    January 6, 2025

    5 Best Torrent Sites for Software in 2025

    January 2, 2025

    1337x Alternatives, Proxies, and Mirror Sites in 2025

    January 2, 2025

    10 Best Torrent Sites for eBooks in 2025 [Working]

    January 2, 2025

    10 Best Anime Torrent Sites in 2025 [Working Sites]

    January 6, 2025

    Top Free Photo Editing Software For PC in 2025

    January 2, 2025
    Pages
    • About
    • Contact
    • Privacy
    • Careers
    Privacy

    Information such as the type of browser being used, its operating system, and your IP address is gathered in order to enhance your online experience.

    © 2013 - 2025 Technotification | All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.