rapier icon indicating copy to clipboard operation
rapier copied to clipboard

Add World/DefaultWorld convenience structs?

Open Johannes0021 opened this issue 7 months ago • 2 comments

I've implemented two new helpers, World and DefaultWorld, that wrap all of Rapier’s setup code without changing any existing APIs. This makes initialization and stepping the simulation much simpler, while keeping the library fully backward-compatible. All existing code and examples remain valid and unchanged; this is purely additive.

Example usage:

use rapier2d::prelude::*;

fn main() {
    let mut world = DefaultWorld::new(vector![0.0, -9.81]);
    let DefaultWorld { rigid_body_set, collider_set, .. } = &mut world;

    /* Create the ground. */
    let collider = ColliderBuilder::cuboid(100.0, 0.1).build();
    collider_set.insert(collider);

    /* Create the bouncing ball. */
    let rigid_body = RigidBodyBuilder::dynamic()
        .translation(vector![0.0, 10.0])
        .build();
    let collider = ColliderBuilder::ball(0.5).restitution(0.7).build();
    let ball_body_handle = rigid_body_set.insert(rigid_body);
    collider_set.insert_with_parent(collider, ball_body_handle, rigid_body_set);

    /* Run the game loop, stepping the simulation once per frame. */
    for _ in 0..200 {
        world.step(&() /* hooks */, &() /* event_handler */);

        let ball_body = &world.rigid_body_set[ball_body_handle];
        println!("Ball altitude: {}", ball_body.translation().y);
    }
}

You can see the code on my branch: https://github.com/Johannes0021/rapier/tree/world_struct

Would adding World/DefaultWorld and the step() method to the core library fit Rapier’s design goals? Or would it be better kept as user-land code? Feedback is welcome.

Johannes0021 avatar May 20 '25 03:05 Johannes0021

  • This is interesting and seems to take a similar approach to https://github.com/dimforge/rapier/pull/796, I'll keep this issue open to go with that PR, or related discussions

ThierryBerger avatar May 21 '25 08:05 ThierryBerger

Ah, I hadn't seen that you were already working on something like this; great work! I had closed the issue earlier because I wasn't entirely sure about how to handle things like BroadPhase, PhysicsHooks, and EventHandler.

Johannes0021 avatar May 21 '25 13:05 Johannes0021