World Module
- class box2d.world.World(gravity: VectorLike = (0, -10), threads: int = 1)[source]
2D physics world containing bodies, joints, and simulation parameters.
Manages Box2D world state and provides body creation through a builder pattern. Wraps Box2D’s b2World functionality with Pythonic interfaces.
Example
>>> world = World(gravity=(0, -9.81)) >>> body = world.new_body().dynamic().position(0, 5).box(1, 1).build() >>> for _ in range(60): ... world.step(1/60, 4)
- __init__(gravity: VectorLike = (0, -10), threads: int = 1)[source]
Initialize physics world with specified gravity vector.
- Parameters:
gravity – Initial gravitational acceleration (x,y) in m/s².
Example
>>> world = World(gravity=(0, -9.8)) >>> world.gravity Vec2(0.0, -9.8)
- add_distance_joint(body_a, body_b, local_anchor_a=None, local_anchor_b=None, collide_connected=False, length=None, min_length=None, max_length=None, enable_limit=False, enable_spring=False, hertz=None, damping_ratio=None, enable_motor=False, motor_speed=None, max_motor_force=None) DistanceJoint[source]
Create a distance joint that maintains or limits distance between points on two bodies.
- Parameters:
body_a – First body to connect (must belong to this world)
body_b – Second body to connect (must belong to this world)
local_anchor_a (tuple) – Local coordinates (x,y) on body_a where joint attaches
local_anchor_b (tuple) – Local coordinates (x,y) on body_b where joint attaches
collide_connected (bool) – Whether bodies can collide with each other
length (float) – Rest length. Calculated from anchors if None.
min_length (float) – Minimum allowed length when using limits
max_length (float) – Maximum allowed length when using limits
enable_limit (bool) – Whether to enable length limits
enable_spring (bool) – Enable spring behavior
hertz (float) – Spring oscillation frequency in Hz
damping_ratio (float) – Spring damping ratio
enable_motor (bool) – Enable the joint motor
motor_speed (float) – Desired motor speed in meters/second
max_motor_force (float) – Maximum motor force in Newtons
- Returns:
The created distance joint
- Return type:
DistanceJoint
Example
>>> world = World() >>> body_a = world.new_body().dynamic().position(0,0).build() >>> body_b = world.new_body().dynamic().position(2,0).build() >>> # Create spring joint >>> spring = world.add_distance_joint( ... body_a, body_b, ... anchor_a=(0,0), ... anchor_b=(2,0), ... enable_spring=True, ... hertz=4.0, ... damping_ratio=0.5 ... ) >>> # Create rope joint >>> rope = world.add_distance_joint( ... body_a, body_b, ... anchor_a=(0,1), ... anchor_b=(2,1), ... enable_limit=True, ... min_length=1.0, ... max_length=3.0 ... )
- add_motor_joint(body_a, body_b, linear_offset=None, angular_offset=None, max_force=None, max_torque=None, correction_factor=None, collide_connected=False) MotorJoint[source]
Create a motor joint to control relative motion between two bodies.
- Parameters:
body_a – First body to connect
body_b – Second body to connect
linear_offset (tuple) – Desired position of bodyB in bodyA’s frame
angular_offset (float) – Desired angle between bodies in radians
max_force (float) – Maximum force in Newtons
max_torque (float) – Maximum torque in Newton-meters
correction_factor (float) – Position correction factor [0,1]
collide_connected (bool) – Whether bodies can collide
- Returns:
The created motor joint
- Return type:
MotorJoint
Example
>>> world = World() >>> ground = world.new_body().build() >>> body = world.new_body().dynamic().position(0, 4).build() >>> motor = world.add_motor_joint( ... ground, body, ... linear_offset=(1, 0), # Move body 1m right ... max_force=100 ... )
- add_mouse_joint(body, target, max_force=1000.0, damping_ratio=0.7, hertz=5) MouseJoint[source]
Create a mouse joint for interactive dragging between bodies
- Parameters:
body – Body to drag
target – Initial target position in world coordinates
max_force – Maximum constraint force (default 1000.0)
damping_ratio – Response damping ratio (0-1, default 0.7)
herts – Spring stiffness in Hz (higher = stiffer movement)
Example
>>> world = World() >>> box = world.new_body().dynamic().position(0,5).build() >>> mouse_joint = world.add_mouse_joint(box, (0,5))
- add_prismatic_joint(body_a, body_b, local_anchor_a=None, local_anchor_b=None, axis=(1, 0), anchor=None, collide_connected=False, lower_limit=None, upper_limit=None, enable_limit=None, motor_speed=None, max_motor_force=None, enable_motor=None, reference_angle=None, enable_spring=None, hertz=None, damping_ratio=None) PrismaticJoint[source]
Create a prismatic joint that allows sliding motion along an axis.
- Parameters:
body_a – First body to connect (must belong to this world)
body_b – Second body to connect (must belong to this world)
local_anchor_a (tuple) – Local coordinates (x,y) on body_a where joint attaches
local_anchor_b (tuple) – Local coordinates (x,y) on body_b where joint attaches
axis (tuple) – The axis defining allowed translation (x,y) in body A’s frame
anchor – World coordinates (x,y) where joint attaches (alternative to local anchors)
collide_connected (bool) – Whether bodies can collide with each other
lower_limit (float) – Lower translation limit
upper_limit (float) – Upper translation limit
enable_limit (bool) – Whether to enable joint limits
motor_speed (float) – Desired motor speed in meters/sec
max_motor_force (float) – Maximum motor force in Newtons
enable_motor (bool) – Whether to enable the joint motor
reference_angle (float) – Reference angle between bodies in radians
enable_spring (bool) – Enable spring behavior
hertz (float) – Spring stiffness frequency in Hz
damping_ratio (float) – Spring damping ratio
- Returns:
The created prismatic joint
- Return type:
PrismaticJoint
Example
>>> world = World() >>> body_a = world.new_body().dynamic().position(0,0).build() >>> body_b = world.new_body().dynamic().position(1,0).build() >>> # Create sliding joint along x-axis >>> joint = world.add_prismatic_joint( ... body_a, body_b, ... anchor=(0.5,0), ... axis=(1,0), ... enable_limit=True, ... lower_limit=-1, ... upper_limit=1 ... )
- add_revolute_joint(body_a, body_b, local_anchor_a=None, local_anchor_b=None, anchor=None, collide_connected=False, lower_angle=None, upper_angle=None, enable_limit=None, motor_speed=None, max_motor_torque=None, enable_motor=None, reference_angle=None) RevoluteJoint[source]
Create a revolute joint connecting two bodies, allowing relative rotation about an anchor point.
- Parameters:
body_a – The first body to connect (must belong to this world).
body_b – The second body to connect (must belong to this world).
local_anchor_a (tuple) – Local coordinates (x, y) on body_a for the joint.
local_anchor_b (tuple) – Local coordinates (x, y) on body_b for the joint.
collide_connected (bool, optional) – Whether the connected bodies should collide with each other. Defaults to False.
lower_angle (float, optional) – Lower joint limit in radians.
upper_angle (float, optional) – Upper joint limit in radians.
enable_limit (bool, optional) – Enable joint limits if True.
motor_speed (float, optional) – Desired motor speed in radians per second.
max_motor_torque (float, optional) – Maximum motor torque in newton-meters.
enable_motor (bool, optional) – Enable the joint motor if True.
reference_angle (float, optional) – Reference angle between the two bodies.
- Returns:
The created revolute joint connecting body_a and body_b.
- Return type:
RevoluteJoint
Example
>>> world = World() >>> body_a = world.new_body().dynamic().position(0, 0).build() >>> body_b = world.new_body().dynamic().position(1, 0).build() >>> revolute_joint = world.add_revolute_joint( ... body_a, body_b, (0, 0), (0, 0), ... collide_connected=False, ... enable_limit=True, ... lower_angle=-0.5, ... upper_angle=0.5 ... )
- add_weld_joint(body_a, body_b, local_anchor_a=None, local_anchor_b=None, anchor=None, collide_connected=False, linear_hertz=None, linear_damping_ratio=None, angular_hertz=None, angular_damping_ratio=None, reference_angle=None) WeldJoint[source]
Create a weld joint that rigidly connects two bodies.
- Parameters:
body_a – The first body to connect (must belong to this world)
body_b – The second body to connect (must belong to this world)
local_anchor_a (tuple) – Local coordinates (x, y) on body_a where the joint attaches.
local_anchor_b (tuple) – Local coordinates (x, y) on body_b where the joint attaches.
anchor – World coordinates (x, y) where the joint attaches. (Used without local anchors)
collide_connected (bool, optional) – If True, the connected bodies will collide.
linear_hertz (float, optional) – Linear spring stiffness in Hertz (0 means rigid).
linear_damping_ratio (float, optional) – Linear damping ratio (non-dimensional).
angular_hertz (float, optional) – Angular spring stiffness in Hertz (0 means rigid).
angular_damping_ratio (float, optional) – Angular damping ratio (non-dimensional).
reference_angle (float, optional) – The body_b angle minus body_a angle in the reference state (radians)
- Returns:
The created weld joint connecting the two bodies.
- Return type:
WeldJoint
Example
>>> world = World() >>> body_a = world.new_body().dynamic().position(0, 0).build() >>> body_b = world.new_body().dynamic().position(1, 1).build() >>> weld_joint = world.add_weld_joint(body_a, body_b, anchor=(0.5, 0.5))
- add_wheel_joint(body_a, body_b, local_anchor_a=None, local_anchor_b=None, axis=(1, 0), anchor=None, collide_connected=False, enable_limit=False, lower_translation=0.0, upper_translation=0.0, enable_motor=False, motor_speed=0.0, max_motor_torque=0.0, enable_spring=False, spring_hertz=0.0, spring_damping_ratio=0.0) WheelJoint[source]
Create a wheel joint for vehicle suspension simulation.
- Parameters:
body_a – First body to connect (must belong to this world)
body_b – Second body to connect (must belong to this world)
local_anchor_a (tuple) – Local coordinates (x,y) on body_a where joint attaches
local_anchor_b (tuple) – Local coordinates (x,y) on body_b where joint attaches
axis (tuple) – The axis defining translation (x,y) in body A’s frame
anchor – World coordinates (x,y) where joint attaches (alternative to local anchors)
collide_connected (bool) – Whether bodies can collide with each other
enable_limit (bool) – Enable translation limits
lower_translation (float) – Lower translation limit
upper_translation (float) – Upper translation limit
enable_motor (bool) – Enable the joint motor
motor_speed (float) – Desired motor speed in radians/sec
max_motor_torque (float) – Maximum motor torque in N-m
enable_spring (bool) – Enable spring behavior
spring_hertz (float) – Spring oscillation frequency in Hz
spring_damping_ratio (float) – Spring damping ratio (non-dimensional)
- Returns:
The created wheel joint
- Return type:
WheelJoint
Example
>>> world = World() >>> chassis = world.new_body().dynamic().position(0,1).box(2,0.5).build() >>> wheel = world.new_body().dynamic().position(1,0).circle(0.4).build() >>> # Create wheel suspension >>> joint = world.add_wheel_joint( ... chassis, wheel, ... anchor=(1,0), ... axis=(0,1), # Vertical suspension movement ... enable_spring=True, ... spring_hertz=4.0, ... spring_damping_ratio=0.7 ... )
- property bodies
Get list of all active bodies in the world.
- Returns:
Copies of registered body references
- Return type:
list[Body]
Example
>>> world = World() >>> box = world.new_body().dynamic().build() >>> len(world.bodies) 1
- property contact_damping_ratio: float
Contact constraint damping ratio (0-1).
1.0 = critical damping (fastest oscillation reduction)
Example
>>> world = World() >>> world.contact_damping_ratio = 0.2 # Add some energy absorption
- property contact_hertz: float
Contact constraint stiffness frequency (Hz).
Higher values make contacts stiffer/more rigid.
Example
>>> world = World() >>> world.contact_hertz = 30.0 # Softer contacts
- property contact_push_velocity: float
Maximum velocity for pushing objects out of penetration (m/s).
Limits how fast contacts can separate penetrating bodies.
Example
>>> world = World() >>> world.contact_push_velocity = 2.0 # Allow faster separation
- draw(debug_draw: DebugDraw)[source]
Render world state using debug drawing interface.
- Parameters:
debug_draw – Configured DebugDraw instance for visualization
Example
>>> world = World() >>> debug_draw = DebugDraw() >>> world.draw(debug_draw)
- property enable_continuous: bool
Toggle continuous collision detection for dynamic vs static bodies.
Helps prevent fast-moving objects from tunneling through static geometry.
Example
>>> world = World() >>> world.enable_continuous = False # Disable CCD for static
- property enable_sleep: bool
Control whether bodies can enter sleep state to save computation.
When enabled, inactive bodies will stop simulating until awakened.
Example
>>> world = World() >>> world.enable_sleep = False # Disable sleeping entirely
- get_sensor_events() list[source]
Retrieve all sensor events that occurred during the last time step.
Sensors are shapes marked with is_sensor=True. They detect overlap with other shapes but don’t generate collision responses. This method returns all begin and end overlap events for sensors from the last simulation step.
- Returns:
- A list of SensorEvent objects with the following attributes:
sensor: The sensor Shape that detected overlap
visitor: The Shape that overlapped with the sensor
begin: True if overlap began, False if overlap ended
- Return type:
list
Example
>>> world = World() >>> body = world.new_body().dynamic().position(0,0).build() >>> # Create a sensor fixture >>> sensor = body.add_circle(radius=1.0, is_sensor=True) >>> # Run simulation >>> world.step(1/60) >>> # Get events >>> events = world.get_sensor_events() >>> for event in events: ... if event['begin']: ... print(f"Sensor began contact with object") ... else: ... print(f"Sensor ended contact with object")
- property gravity
World gravity vector (m/s²).
Example
>>> world = World() >>> world.gravity = (0, -9.81) >>> world.gravity Vec2(0.0, -9.81)
- property hit_event_threshold: float
Minimum collision speed to trigger hit events (m/s).
Collisions slower than this won’t generate collision events.
Example
>>> world = World() >>> world.hit_event_threshold = 0.5 # Get events for slower impacts
- new_body()[source]
Create BodyBuilder for constructing bodies. Entry point for body creation.
- Returns:
Fluent interface for body configuration
- Return type:
Example
>>> world = World() >>> builder = world.new_body() >>> body = builder.dynamic().position(2,3).circle(1).build()
- query_aabb(aabb: AABB, collision_filter: CollisionFilter = None, max_results: int = None) list[source]
Find shapes overlapping an axis-aligned bounding box using an optional collision filter.
- Parameters:
aabb – Axis-aligned bounding box to query.
collision_filter – Optional CollisionFilter instance for filtering. If None, a default CollisionFilter is used.
max_results – Optional maximum number of shapes to return. The callback will return False when this limit is reached.
- Returns:
Shapes with overlapping fixtures.
- Return type:
list
Example
>>> world = World() >>> box = world.new_body().dynamic().position(0, 0).box(1, 1).build() >>> aabb = AABB(lower=Vec2(-1, -1), upper=Vec2(1, 1)) >>> overlaps = world.query_aabb(aabb, collision_filter=CollisionFilter(), max_results=10) >>> len(overlaps) <= 10 True
- query_circle(position: VectorLike, radius: float, collision_filter: CollisionFilter = None, max_results: int = None) list[source]
Find shapes overlapping a circle.
- Parameters:
position – Center of the query circle in world coordinates.
radius – Radius of the query circle.
collision_filter – Optional CollisionFilter instance for filtering. If None, a default CollisionFilter is used.
max_results – Optional maximum number of shapes to return. The callback will return False when this limit is reached.
- Returns:
Shapes with overlapping fixtures.
- Return type:
list
Example
>>> world = World() >>> # Create a body with a circle fixture >>> box = world.new_body().dynamic().circle(1).build() >>> overlaps = world.query_circle((0, 0), 1.5, collision_filter=CollisionFilter(), max_results=10) >>> len(overlaps) <= 10 True
- ray_cast(origin: VectorLike, translation: VectorLike, collision_filter: CollisionFilter = None, first_hit_only: bool = False) list[RayCastResult][source]
Cast a ray and find intersecting shapes.
- Parameters:
origin – Starting point of the ray (x,y)
translation – The translation of the ray from the start point to the end point
collision_filter – Optional filter to control which shapes are tested
first_hit_only – If True, only return the first hit encountered
- Returns:
List of RayCastResult objects containing hit information
Example
>>> world = World() >>> box = world.new_body().dynamic().position(5,0).box(1,1).build() >>> hits = world.ray_cast((0,0), (10,0)) >>> len(hits) > 0 True >>> hits[0].shape # First intersected shape <Shape>
- property restitution_threshold: float
Minimum collision speed for restitution effects (m/s).
Collisions slower than this threshold will have zero restitution.
Example
>>> world = World() >>> world.restitution_threshold = 2.0 # Only apply restitution above 2m/s
- step(time_step, substep_count=4)[source]
Advance simulation by time step.
- Parameters:
time_step – Time to simulate (seconds)
substep_count – Number of solver iterations (default 4) Higher values improve stability at cost of performance
Example
>>> world = World() >>> world.step(1/60) # Default 4 substeps >>> world.step(0.016, 6) # Custom substep count