Recent from talks
Nothing was collected or created yet.
Box2D
View on Wikipedia
| Box2D | |
|---|---|
Current Box2D logo | |
| Developer | Erin Catto |
| Initial release | September 11, 2007 |
| Stable release | 3.1.1 |
| Repository | |
| Written in | C |
| Operating system | OS independent |
| Type | Middleware |
| License | MIT (since version 2.4.0)[2]
zlib License |
| Website | www |
Box2D is a free open source 2-dimensional physics simulator engine written in C by Erin Catto and published under the MIT license. It has been used in Crayon Physics Deluxe, Limbo, Rolando, Incredibots, Angry Birds, Tiny Wings, Shovel Knight, Transformice, Happy Wheels,[3] and many online Flash games,[4] as well as iPhone, iPad and Android games using the Cocos2d or Moscrif game engine and Corona framework. It has also been used in the Unity game engine.
History
[edit]Box2D was first released as "Box2D Lite", a demonstration engine to accompany a physics presentation given by Erin Catto at GDC 2006. On September 11, 2007, it was released as open source on SourceForge. On January 17, 2010, Box 2D moved the project to Google Code for hosting.[5] On July 12, 2015, hosting was moved again, this time to GitHub.[6]
On March 6, 2008, version 2.0 was launched, introducing continuous collision detection and revamping the API.
On July 27, 2020, version 2.4 was launched, with a variety of changes, most notably the license was changed to the MIT License.[7]
Cross-platform availability
[edit]Box2D is itself written in platform-independent C (usable on any system with a C compiler available). The engine may be compiled in fixed point and floating point modes, and has been used on the Nintendo DS, Wii, and several mobile phones (including Android, BlackBerry 10 and iOS) as well as most major operating systems.
The engine has been ported to many other programming languages and environments, including Java,[8] Adobe Flash (in ActionScript[9] and Haxe[10] languages), C#,[11] Lua, JavaScript,[12][13] and D.[14] Bindings exist to use the compiled library from Python,[15] DarkBASIC and BBC BASIC.
On October 30, 2009, it was announced that Box2D was being integrated into the (now older) Torque 2D game engine.[16]
Programs that use the engine
[edit]- BBC Basic for SDL, cross-platform version of BBC Basic
- BlitzBasic
- GameMaker: Studio, uses the engine for physics simulation.
- LibGDX, uses the physics engine for games and lighting.
- Stencyl, uses the physics engine for games, and allows export to Flash and iOS.
- Unity
- Construct2
- LÖVE, uses the physics engine for games[17]
- Solar2D
- Clickteam Fusion 2.5
- Flame, Flutter game engine
Features
[edit]Box2D performs constrained rigid body simulation. It can simulate bodies composed of convex polygons, circles, and edge shapes. Bodies are joined with joints and acted upon by forces. The engine also applies gravity, friction, and restitution.
Box2D's collision detection and resolution system consists of three pieces: an incremental sweep and prune broad phase, a continuous collision detection unit, and a stable linear-time contact solver. These algorithms allow efficient simulations of fast bodies and large stacks without missing collisions or causing instabilities.[18]
Related engines
[edit]An earlier version of the Box2D engine, now known as Box2D Lite, was released primarily for educational purposes, based on a series of yearly Game Developers Conference presentations that Erin Catto has given. Box2D Lite uses many of the same algorithms as Box2D, but has a smaller feature set.
The Chipmunk physics engine (written in C)[19] and Phys2D (written in Java)[20] are both partially based on Box2D Lite. The physics engine used in SpriteKit for iOS and OS X uses Box2D internally.[21]
The LiquidFun physics engine is a fork of Box2D by Google,[22] which adds fluid simulation to the engine.
LibGDX uses a Java wrapper around native Box2D code written in C as its physics engine.[23]
Articles
[edit]Itterheim and Wenderlich describe the usage of Box2D in the Cocos2d iPhone engine.[24][25] An article in the Adobe Edge newsletter discusses the use of Box2D in Flash games.[26]
See also
[edit]References
[edit]- ^ Erin Catto. "Latest Release". GitHub.
- ^ "Box2D on GitHub". GitHub. October 15, 2021.
- ^ "Play Happy Wheels Online – AndroidFantasy". Archived from the original on September 5, 2015. Retrieved August 14, 2015.
- ^ "Box2d Games at Jayisgames". Jayisgames.
- ^ "Box2D – Home". Box2D. Archived from the original on October 23, 2007.
- ^ "GitHub Hosting | Box2D". box2d.org. Archived from the original on April 6, 2018. Retrieved April 6, 2018.
- ^ "Release v2.4.0". github.com. Retrieved August 14, 2020.
- ^ "JBox2D: A Java Physics Engine". JBox2D.
- ^ "AS3 Flash Physics Engine Box2DFlashAS3 2.0.1". Box2D.
- ^ "Google Code Archive – Long-term storage for Google Code Project Hosting".
- ^ "Google Code Archive – Long-term storage for Google Code Project Hosting".
- ^ "Box2DJS". Box2D.
- ^ "GitHub – hecht-software/box2dweb: Automatically exported from code.google.com/p/box2dweb". GitHub. September 16, 2021.
- ^ "blaze". Dsource.
- ^ "Pybox2d/pybox2d: 2D Game Physics for Python". GitHub. Retrieved February 19, 2016.
- ^ Perry, Michael (October 30, 2009). "Torque 2D Development Blog – Box2D Overview". garagegames.com. Retrieved February 26, 2016.
- ^ "Love.physics - LOVE".
- ^ "Chapter 1 Introduction". Box2D. Archived from the original on March 27, 2009.
- ^ "Google Code Archive – Long-term storage for Google Code Project Hosting".
- ^ "Index of /phys2d". Coke and Code.
- ^ "tm4ko – Ghostbin". Ghostbin. Archived from the original on July 27, 2013.
- ^ "LiquidFun". google.github.io. Retrieved March 12, 2017.
- ^ "Physics · libgdx/Libgdx Wiki". GitHub.
- ^ Steffen Itterheim. (2010). "Learn iPhone and iPad cocos2d Game Development." Apress.
- ^ Rod Strougo and Ray Wenderlich. (2011). "Learning Cocos2d: A Hands-On Guide to Building IOS Games with Cocos2d, Box2d, and Chipmunk." Addison-Wesley Professional.
- ^ "Adobe Edge: April 2010 – Developing physics-based games with Adobe Flash Professional". Adobe. Archived from the original on August 11, 2011. Retrieved July 19, 2016.
External links
[edit]Box2D
View on GrokipediaHistory and Development
Origins and Initial Release
Box2D's development began with Erin Catto's presentation at the 2005 Game Developers Conference (GDC) on "Iterative Dynamics," which introduced foundational concepts for constraint-based physics simulations.[4] Box2D was created by Catto, a software engineer at Crystal Dynamics who specialized in physics simulation for video games, including the engine for Tomb Raider: Legend.[5] In 2006, Catto presented at the Game Developers Conference (GDC) on rigid body dynamics, introducing key concepts in constraint-based physics solvers to help game developers implement efficient simulations.[2] Accompanying this GDC 2006 tutorial, Catto released Box2D Lite, a simplified 2D physics engine designed as a demonstration tool to illustrate sequential impulses for handling collisions, friction, stacking, and joints.[6] The engine emphasized fast and robust physics with minimal code, allowing developers to experiment with realistic object interactions in a 2D environment without the overhead of full 3D systems.[5] The initial goals of Box2D centered on providing an accessible simulation framework for game developers, prioritizing stability in scenarios like object stacking and joint constraints over complex numerical methods, to enable realistic 2D physics in resource-constrained game environments.[5] As an educational resource, Box2D Lite quickly saw early adoption in game prototypes, transitioning from a tutorial demo into a more comprehensive library by 2007 to support broader development needs.[10] On September 10, 2007, Catto open-sourced the full Box2D project on SourceForge under the zlib/libpng license, marking its evolution into a freely available tool for the game development community.[11]Version History and Major Updates
Box2D's version history reflects iterative enhancements in stability, performance, and usability, with major releases building on the foundational v2.0 introduced in 2008 as a full engine expansion from the earlier Lite demonstration.[12] Version 2.3, released in November 2013, delivered key stability improvements, including refined collision detection and solver robustness to reduce simulation artifacts in complex scenarios.[13] In 2010, v2.1 facilitated the project's migration to Google Code for improved collaboration and distribution. A significant licensing shift occurred with v2.4.0 in July 2020, transitioning from the zlib license to the more permissive MIT License, which broadened adoption by simplifying integration into diverse projects.[14] This was followed by v2.4.1 in October 2020, which included bug fixes. The final v2 release, v2.4.2 in August 2024, incorporated minor optimizations while marking the end of the v2 lineage to pave the way for a comprehensive overhaul.[15][16] The transition to v3.0 in August 2024 represented a complete rewrite, shifting from C++ to C for better portability and maintainability, alongside a simplified API that streamlined body and fixture management.[17] This version improved solver efficiency through algorithmic refinements and overhauled continuous collision detection, replacing legacy methods with a hybrid speculative and time-of-impact approach for more reliable fast-moving object handling.[17] Subsequent updates refined v3, with v3.1 in April 2025 addressing bugs from the initial rewrite, introducing enhanced joint types such as improved distance and wheel constraints, and adding support for custom SIMD instructions (SSE2/Neon) to boost performance on modern hardware.[18] Version 3.1.1, released in June 2025, included further bug fixes and minor API adjustments for stability. These v3 updates yielded measurable performance gains, including a 20% speedup in the core GJK collision algorithm, contributing to 20-30% faster overall simulations on average hardware in benchmark tests.[18][19]Technical Overview
Core Architecture
Box2D's core architecture centers on a rigid body simulation model that treats physical objects as rigid bodies with fixed shapes and constant mass distribution. Each body is defined by its position, linear and angular velocity, mass, and moment of inertia, and can be classified as dynamic (affected by forces and collisions), static (immovable), or kinematic (position-controlled). The simulation world serves as the central container, managing a collection of bodies, handling time advancement, and orchestrating broad-phase collision detection to identify potential interactions efficiently.[20][21] The constraint solver forms the heart of Box2D's dynamics, employing the Soft Step solver in version 3, which uses sub-stepping and soft constraints to resolve velocity and position constraints arising from contacts and joints. This approach improves stability for high mass ratios, long chains, and large stacks compared to earlier versions. The solver operates in O(N time where N is the number of constraints, enabling stable simulations of complex interactions. Version 3 also introduces multithreading for broad-phase and contact solving, along with SIMD optimizations (SSE2 by default, optional AVX2) for enhanced performance on modern hardware.[22][17][23] Time advancement in Box2D follows a discrete time-stepping loop with a fixed time step, commonly set to 1/60 seconds for 60 Hz simulations, to maintain determinism and stability. It employs semi-implicit Euler integration, first updating velocities from accelerations (including gravity and applied forces) and then positions from the new velocities, as expressed by the equations: where is linear velocity, is position, is the time step, and is total acceleration. This approach, combined with sub-stepping for variable frame rates, prevents instability in high-speed scenarios.[21][20][24] Broad-phase collision detection utilizes a dynamic AABB tree, a balanced binary tree structure where each node represents an axis-aligned bounding box (AABB) enclosing child nodes or leaf shapes. This hierarchy enables efficient pairwise overlap queries by traversing the tree, achieving near complexity for objects instead of , thus scaling well for large scenes with thousands of bodies. Updates to the tree occur incrementally as bodies move, minimizing rebuild costs. In version 3, the broad-phase supports multithreading for better scalability.[25][26][17] Memory management in Box2D emphasizes performance through a stack allocator for temporary workspace during each simulation step, allocating a fixed-size block (e.g., 100 KB) to avoid heap allocations and deallocations per frame. Persistent objects like bodies and shapes use a block allocator for larger, long-lived memory, while opaque IDs facilitate safe, cache-friendly access without direct pointers. This design reduces fragmentation and latency in real-time applications. The version 3 rewrite adopts a data-oriented design in portable C17, hiding internal data structures for better optimization.[27][28][17]Key Features and Capabilities
Box2D provides robust collision detection mechanisms, supporting both discrete and continuous methods to handle interactions between rigid bodies in 2D simulations. Discrete collision detection resolves overlaps at fixed time steps, while continuous detection in version 3 employs a hybrid speculative and time-of-impact (TOI) approach to prevent tunneling, particularly for fast-moving objects, with improved precision for worlds up to ~20 km. Supported shapes include circles, convex polygons limited to a maximum of 8 vertices, edges (segments), chains of edges, capsules, and rounded polygons (new in v3.0), allowing multiple shapes per body with collision filtering to selectively enable or disable interactions. Contact manifolds are generated to represent collision points and normals, facilitating impulse-based resolution for realistic responses.[7][17] The engine offers a variety of joints and constraints to model mechanical connections between bodies, including revolute joints for rotational pivots, prismatic joints for sliding motion, distance joints to maintain a fixed separation, motor joints for applying drive forces (with motor added to distance joint in v3), and mouse joints. Additional joint types encompass weld and wheel joints, each supporting optional limits, motors with target velocities and maximum forces/torques, springs (added to many joints in v3, characterized by stiffness in Hertz and damping ratio), and friction. For the distance joint, the constraint enforces , where and are anchor points on the connected bodies and is the target distance; this is solved using the constraint solver to compute corrective impulses.[21][7][4][17] Forces and effects in Box2D simulate realistic dynamics, with built-in support for global gravity applied uniformly to dynamic bodies, as well as user-applied linear forces, torques, and impulses for precise control. Friction is modeled using a single coefficient, with the solver simulating both static (sticking) and dynamic (sliding) behavior at contacts, while restitution coefficients ranging from 0 (perfectly inelastic) to 1 (perfectly elastic) determine bounciness during collisions. To optimize performance, the engine implements island-based sleeping, where inactive bodies—those with near-zero velocity and no external forces—are deactivated to reduce computational load until awakened by interactions.[7][23][4] Sensors and queries enable efficient spatial testing without full simulation overhead. Ray casting traces lines through the world to detect intersections, useful for line-of-sight checks or targeting, returning hit points, normals, and fractions along the ray. Shape queries test for overlaps with existing bodies or fixtures, supporting broad-phase culling via a dynamic tree structure for scalability. Sensor fixtures, which report overlaps without generating impulses, trigger begin/end events for proximity detection in gameplay logic. Version 3.1 introduces an improved sensor system that operates independently of body type or sleep status, running at the end of updates for reliable, multithreaded, and deterministic touch events.[7][18] Advanced capabilities extend Box2D's utility for complex simulations. Destructible bodies can be achieved via fracturing algorithms that break polygons into child shapes upon impact, maintaining physical integrity by reattaching fragments with joints or discarding debris. These techniques leverage the core solver's velocity and position constraints for emergent behaviors like shattering objects. Version 3.1 adds an experimental character mover using a geometric solver for precise control outside the main physics world, useful for games requiring custom character physics.[7][18]Implementation and Platforms
Programming Languages and Bindings
Box2D's native implementation is provided as a portable C library since version 3.0, requiring a compiler that supports C17 or later, with header-only options available for easier integration.[17] The core API revolves around opaque handles such asb2WorldId for managing the physics simulation, b2BodyId for representing rigid bodies, and shape creation functions like b2CreateCircleShape or b2CreatePolygonShape, replacing the earlier b2Fixture class from version 2.x.[29] Bodies are defined using structures like b2BodyDef, which specify properties such as position, type, and linear velocity, before being created via factory functions like b2CreateBody.[7]
There are no official bindings beyond the native C API, as the project maintainer focuses solely on the C implementation without support for wrappers in other languages.[8] Community-driven ports extend Box2D's accessibility, including the Python binding box2d-python which supports core features of version 3.0 and is under active development, while the older PyBox2D (version 2.3.x) targets version 2.x but has seen updates for partial v3 compatibility.[30] For Java, the libGDX framework provides bindings via its gdx-box2d extension, which wraps the C library and supports version 3.1.1 as of recent updates.[31] In C#, community efforts like Box2D-dotnet-bindings offer bindings for .NET languages (C#, F#, VB.NET) compatible with Box2D 3.x, building on earlier projects such as Box2DX for version 2.x.[32]
The API structure emphasizes a functional, handle-based design for advancing the simulation and object management. Developers advance the physics world using the b2World_Step function, typically called as b2World_Step(worldId, timeStep, subStepCount), where timeStep is the delta time in seconds, and subStepCount (recommended at 4) controls internal solver iterations for balancing accuracy and performance—a shift from version 2.x's explicit velocityIterations (10–20) and positionIterations (3–8) parameters.[29] Object creation follows a definition-factory pattern, such as initializing a b2BodyDef, setting its fields (e.g., def.type = e_dynamicBody), and passing it to b2CreateBody(worldId, &def) to obtain a b2BodyId.[7]
Version 3.0 introduced significant API simplifications, including a full rewrite from C++ to C for better portability and ease of binding, while removing polymorphism in shapes (e.g., eliminating the b2Shape base class hierarchy) in favor of direct primitive creation functions and variant-like handling via unions or specific APIs for efficiency.[17] This reduces overhead and callback complexity, with shapes now attached directly to bodies without intermediate fixtures, streamlining code for common use cases like polygon or circle colliders.[29]
Best practices for using the API include adhering to SI units—meters for length, kilograms for mass, and seconds for time—to ensure consistent simulation behavior, with typical object scales between 0.1 and 10 meters and world extents under 12 kilometers to avoid precision issues.[1] For the solver, developers should tune the sub-step count based on the application's performance needs, starting with 4 sub-steps per frame to maintain stability without excessive computation, echoing the v2.x trade-off between velocity/position iterations for contact resolution accuracy versus frame rate.[17]
