box2d README

The project's README from github.com/erincatto/box2d. As one markdown file: README.md.

Box2D

Box2D is a 2D physics engine for games.

Box2D Logo

Box2D Version 3.0 Release Demo

Build Status

Build Status

Features

Collision

Physics

System

Samples

Building All Platforms

Building with CMake presets

The presets in CMakePresets.json give one build flow on every platform and are picked up automatically by Visual Studio, VS Code, and CLion (open the folder and choose a preset). From the command line:

Use the *-debug build presets for a debug build (not recommended for the replay viewer). The presets use the default native toolchain (the installed Visual Studio on Windows, Make on Linux, Xcode on macOS), so no specific compiler version is required.

Building for Visual Studio

Building for Linux

Building for Xcode

Building and installing

Installing also provides a pkg-config file, so pkg-config --modversion box2d reports the installed version and pkg-config --cflags --libs box2d gives the build flags.

Building with zig

Fetch and link Box2D from a Zig project:

In build.zig:

const box2d_dep = b.dependency("box2d", .{});
exe.root_module.addImport("box2d", box2d_dep.module("box2d"));

In Zig code, start using box2d

const box2d = @import("box2d");

pub fn main(init: std.process.Init) !void {
    var world_def = box2d.b2DefaultWorldDef();
    world_def.gravity.y = 9.8;
    const world_id = box2d.b2CreateWorld(&world_def);
}

Building with Swift Package Manager

Add box2d as a dependency in your Package.swift:

.package(url: "https://github.com/erincatto/box2d.git", from: "main")

And add the product to your target:

.target(
    name: "MyGame",
    dependencies: [.product(name: "box2d", package: "box2d")]
),

In Swift code, the C API is imported directly:

import box2d

var worldDef = b2DefaultWorldDef()
let worldId = b2CreateWorld(&worldDef)

C structs are passed as inout arguments using &.

Replay viewer

The samples app doubles as a viewer for Box2D recordings (.b2rec files). Any preset above builds it. Pass a recording on the command line to open it directly:

On Windows you can also drag a .b2rec file onto samples.exe. The viewer runs from any directory. Without an argument, open a recording from the Replay menu. See docs/recording.md for how to make a recording.

Compatibility

The Box2D library and samples build and run on Windows, Linux, and Mac.

You will need a compiler that supports C17 to build the Box2D library.

You will need a compiler that supports C++20 to build the samples.

Box2D uses SSE2 and Neon (AArch64) SIMD math to improve performance. This can be disabled by defining BOX2D_DISABLE_SIMD.

Documentation

Community

Contributing

Please do not submit pull requests. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server.

Giving feedback

Please file an issue or start a chat on discord. You can also use GitHub Discussions.

License

Box2D is developed by Erin Catto and uses the MIT license.

Sponsorship

Support development of Box2D through Github Sponsors.

Please consider starring this repository and subscribing to my YouTube channel.

LLM Usage

LLMs are used in the following areas:

Elsewhere all code is developed and written by me. I take responsibility for every line of code in Box2D/3D.

External ports, wrappers, and bindings (unsupported)

box2d (erincatto/box2d)

Searching Database…

10.4K ·GitHub
Что это такое?Box2D — это физический движок для 2D-игр, который отвечает за обнаружение столкновений, динамику твёрдых тел и соединения, чтобы вы могли реалистично моделировать физику в игре.
Это полноценный игровой движок или просто физическая библиотека, которую я подключаю к своему проекту?Это библиотека на C, которую вы собираете и подключаете к своей игре или движку. Она написана на переносимом C17. Это не самостоятельный движок и не редактор.
Как собрать Box2D и добавить его в проект?Установите CMake и git, затем используйте входящие пресеты CMake, например 'cmake --preset windows', после чего 'cmake --build --preset windows-release' (аналогичные пресеты linux-release/macos тоже есть), или соберите вручную командами 'cmake .. && cmake --build . && cmake --install .'.
Что нужно установить перед сборкой?Нужны CMake и git на всех платформах, а также компилятор с поддержкой C17 для самой библиотеки. Для сборки входящего приложения с примерами дополнительно нужен компилятор с поддержкой C++20.
Работает ли это только на определённых платформах?Библиотека и примеры собираются и работают в Windows, Linux и macOS с родными инструментами сборки (соответственно Visual Studio, Make, Xcode).
Можно ли использовать Box2D из Zig или Swift вместо C/C++?Да, его можно получить как пакет Zig командой 'zig fetch --save git+...' или добавить как зависимость через Swift Package Manager. В Swift C API импортируется напрямую, а структуры передаются с '&' как аргументы inout.
Для чего нужен просмотрщик повторов?Приложение с примерами также служит просмотрщиком записанных физических сессий (файлов .b2rec). Передайте запись в командной строке или перетащите её на samples.exe в Windows, чтобы воспроизвести.
Какие формы и соединения поддерживаются?Поддерживаются выпуклые многоугольники, капсулы, круги, скруглённые многоугольники и цепочки. Также поддерживаются вращательные, призматические, дистанционные, соединения для перетаскивания мышью, сварные и колёсные соединения с ограничениями, моторами, пружинами и трением.
Использует ли оно многопоточность или SIMD для ускорения?Да, Box2D активно использует многопоточность и SIMD-вычисления SSE2/Neon для повышения производительности. При необходимости это можно отключить флагом сборки.
Creator
erincatto
Size
17.9 MB
Stars
10.4K
Age
11y
Commits · 90 Days