From a78d4b0387e3aea8f6dbf7eead1dd792c3782e29 Mon Sep 17 00:00:00 2001 From: hut Date: Mon, 1 Apr 2024 20:38:28 +0200 Subject: [PATCH] handle parents in `position_to_transform`, like in bevy_xpbd --- src/world.rs | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/src/world.rs b/src/world.rs index b204f9e..722b1e4 100644 --- a/src/world.rs +++ b/src/world.rs @@ -272,20 +272,55 @@ fn handle_cheats( // A variant of bevy_xpbd_3d::plugins::position_to_transform that adjusts // the rendering position to center entities at the player camera. // This avoids rendering glitches when very far away from the origin. -// -// NOTE: This currently does not support parent objects. pub fn position_to_transform( q_player: Query<&Position, With>, - mut q_trans: Query<(&mut Transform, &Position, &Rotation)>, + mut q_trans: Query<(&'static mut Transform, &'static Position, &'static Rotation, Option<&'static Parent>)>, + parents: Query<(&'static GlobalTransform, Option<&'static Position>, Option<&'static Rotation>), With>, ) { if let Ok(player_pos) = q_player.get_single() { - for (mut transform, pos, rot) in &mut q_trans { + for (mut transform, pos, rot, parent) in &mut q_trans { + if let Some(parent) = parent { + if let Ok((parent_transform, parent_pos, parent_rot)) = parents.get(**parent) { + // Compute the global transform of the parent using its Position and Rotation + let parent_transform = parent_transform.compute_transform(); + let parent_pos = parent_pos.map_or(parent_transform.translation, |pos| { + pos.as_vec3() + // NOTE: I commented out this because it turns a vec3 to a vec4, + // and I don't understand why bevy_xpbd would do that. + //.extend(parent_transform.translation.z) + }); + let parent_rot = parent_rot.map_or(parent_transform.rotation, |rot| { + rot.as_quat() + }); + let parent_scale = parent_transform.scale; + let parent_transform = Transform::from_translation(parent_pos) + .with_rotation(parent_rot) + .with_scale(parent_scale); + + // The new local transform of the child body, + // computed from the its global transform and its parents global transform + let new_transform = GlobalTransform::from( + Transform::from_translation( + pos.as_vec3() + // NOTE: I commented out this because it turns a vec3 to a vec4, + // and I don't understand why bevy_xpbd would do that. + //.extend(parent_pos.z + transform.translation.z * parent_scale.z), + ) + .with_rotation(rot.as_quat()), + ) + .reparented_to(&GlobalTransform::from(parent_transform)); + + transform.translation = new_transform.translation; + transform.rotation = new_transform.rotation; + } + } else { transform.translation = Vec3::new( (pos.x - player_pos.x) as f32, (pos.y - player_pos.y) as f32, (pos.z - player_pos.z) as f32, ); transform.rotation = rot.as_quat(); + } } } }