aboutsummaryrefslogtreecommitdiff
path: root/examples2d/add_remove2.rs
blob: cb7102597a8643b8d5330aec4175b39b7a4111f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use na::Point2;
use rapier2d::dynamics::{JointSet, RigidBodyBuilder, RigidBodySet};
use rapier2d::geometry::{ColliderBuilder, ColliderSet};
use rapier_testbed2d::Testbed;

pub fn init_world(testbed: &mut Testbed) {
    let bodies = RigidBodySet::new();
    let colliders = ColliderSet::new();
    let joints = JointSet::new();
    let rad = 0.5;

    // Callback that will be executed on the main loop to handle proximities.
    testbed.add_callback(move |window, graphics, physics, _, _| {
        let rigid_body = RigidBodyBuilder::new_dynamic()
            .translation(0.0, 10.0)
            .build();
        let handle = physics.bodies.insert(rigid_body);
        let collider = ColliderBuilder::cuboid(rad, rad).build();
        physics
            .colliders
            .insert(collider, handle, &mut physics.bodies);

        if graphics.is_some() {
            graphics
                .unwrap()
                .add(window.unwrap(), handle, &physics.bodies, &physics.colliders);
        }

        let to_remove: Vec<_> = physics
            .bodies
            .iter()
            .filter(|(_, b)| b.position().translation.vector.y < -10.0)
            .map(|e| e.0)
            .collect();
        for handle in to_remove {
            physics
                .bodies
                .remove(handle, &mut physics.colliders, &mut physics.joints);

            // FIXME: need a way to access graphics & window in a loop
            // if graphics.is_some() {
            //     graphics.unwrap().remove_body_nodes(window.unwrap(), handle);
            // }
        }
    });

    /*
     * Set up the testbed.
     */
    testbed.set_world(bodies, colliders, joints);
    testbed.look_at(Point2::new(0.0, 0.0), 20.0);
}

fn main() {
    let testbed = Testbed::from_builders(0, vec![("Add-remove", init_world)]);
    testbed.run()
}