Skip to main content

bevy_rapier2d/utils/
mod.rs

1use crate::math::{Rot, Vect};
2use bevy::prelude::Transform;
3use rapier::math::Pose;
4
5/// Builds a Rapier [`Pose`] from a translation/rotation pair using bevy_rapier's [`Vect`] / [`Rot`] aliases.
6#[cfg(feature = "dim2")]
7pub(crate) fn pose_from(translation: Vect, rotation: Rot) -> Pose {
8    Pose::new(translation, rotation)
9}
10
11/// Builds a Rapier [`Pose`] from a translation/rotation pair using bevy_rapier's [`Vect`] / [`Rot`] aliases.
12#[cfg(feature = "dim3")]
13pub(crate) fn pose_from(translation: Vect, rotation: Rot) -> Pose {
14    Pose::from_parts(translation, rotation)
15}
16
17/// Converts a Rapier pose to a Bevy transform.
18#[cfg(feature = "dim2")]
19pub fn iso_to_transform(iso: &Pose) -> Transform {
20    Transform {
21        translation: iso.translation.extend(0.0),
22        rotation: bevy::prelude::Quat::from_rotation_z(iso.rotation.angle()),
23        ..Default::default()
24    }
25}
26
27/// Converts a Rapier pose to a Bevy transform.
28#[cfg(feature = "dim3")]
29pub fn iso_to_transform(iso: &Pose) -> Transform {
30    Transform {
31        translation: iso.translation,
32        rotation: iso.rotation,
33        ..Default::default()
34    }
35}
36
37/// Converts a Bevy transform to a Rapier pose.
38#[cfg(feature = "dim2")]
39pub(crate) fn transform_to_iso(transform: &Transform) -> Pose {
40    use bevy::math::Vec3Swizzles;
41    Pose::new(
42        transform.translation.xy(),
43        transform.rotation.to_scaled_axis().z,
44    )
45}
46
47/// Converts a Bevy transform to a Rapier pose.
48#[cfg(feature = "dim3")]
49pub(crate) fn transform_to_iso(transform: &Transform) -> Pose {
50    Pose::from_parts(transform.translation, transform.rotation)
51}
52
53#[cfg(test)]
54#[cfg(feature = "dim3")]
55mod tests {
56    use super::*;
57    use bevy::prelude::Transform;
58
59    #[test]
60    fn convert_back_to_equal_transform() {
61        let transform = Transform {
62            translation: bevy::prelude::Vec3::new(-2.1855694e-8, 0.0, 0.0),
63            rotation: bevy::prelude::Quat::from_xyzw(0.99999994, 0.0, 1.6292068e-7, 0.0)
64                .normalize(),
65            ..Default::default()
66        };
67        let converted_transform = iso_to_transform(&transform_to_iso(&transform));
68        assert_eq!(converted_transform, transform);
69    }
70}