appl/
rigidbody.rs

1use rapier2d::{
2  na::Vector2,
3  prelude::*,
4};
5
6use crate::{
7  vector::Vect2,
8  world::ApplWorld,
9};
10
11/// Rigid body types
12#[derive(Debug, Clone, Copy)]
13pub enum BodyType {
14  Dynamic,
15  Static,
16}
17/// Collider shapes
18#[derive(Debug, Clone, Copy)]
19pub enum BodyShape {
20  Cuboid { width: f32, height: f32 },
21  Circle { radius: f32 },
22}
23impl ApplWorld {
24  /// Adds a rigid body to the world
25  pub fn add_rigid_body(
26    &mut self,
27    rigid_body_type: BodyType,
28    collider_shape: BodyShape,
29    restitution: f32,
30    position: Vect2<f32>,
31  ) -> RigidBodyHandle {
32    let position: Vector2<f32> = position.into();
33
34    let rigid_body_type = match rigid_body_type {
35      BodyType::Dynamic => RigidBodyType::Dynamic,
36      BodyType::Static => RigidBodyType::Static,
37    };
38    let collider_shape = match collider_shape {
39      BodyShape::Cuboid { width, height } => {
40        SharedShape::cuboid(width / 2.0 / self.scale, height / 2.0 / self.scale)
41      },
42      BodyShape::Circle { radius } => SharedShape::ball(radius / self.scale),
43    };
44
45    let rigid_body = RigidBodyBuilder::new(rigid_body_type)
46      .translation(position / self.scale)
47      .build();
48    let collider = ColliderBuilder::new(collider_shape)
49      .restitution(restitution)
50      .build();
51    let rb_handle = self.rigid_bodies.insert(rigid_body);
52    self
53      .colliders
54      .insert_with_parent(collider, rb_handle, &mut self.rigid_bodies);
55
56    rb_handle
57  }
58
59  /// Returns a reference to the rigid body using the rigid body handle
60  pub fn get_rigid_body(&self, handle: RigidBodyHandle) -> &RigidBody { &self.rigid_bodies[handle] }
61
62  /// Returns the position of a rigid body got using the rigid body handle
63  pub fn get_rigid_body_pos(&self, handle: RigidBodyHandle) -> Vect2<f32> {
64    ((&self.rigid_bodies[handle]).translation() * self.scale).into()
65  }
66}