From 209576bc18d1bbd74ff092b1ff6c6ad9619eae86 Mon Sep 17 00:00:00 2001 From: copygirl Date: Wed, 22 Oct 2025 11:24:39 +0200 Subject: [PATCH] Add `Blocks.position` function --- src/block.rs | 8 ++++++++ src/placement.rs | 8 ++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/block.rs b/src/block.rs index 71c8274..00b675b 100644 --- a/src/block.rs +++ b/src/block.rs @@ -8,6 +8,7 @@ pub struct Block; pub struct Blocks<'w, 's> { commands: Commands<'w, 's>, block_resources: Res<'w, BlockResources>, + blocks: Query<'w, 's, &'static Transform, With>, } impl Blocks<'_, '_> { @@ -19,6 +20,13 @@ impl Blocks<'_, '_> { Transform::from_translation(pos.as_vec3() + Vec3::ONE / 2.), )); } + + /// Gets the position of a block entity, or `None` + /// if the given entity is not alive or not a block. + pub fn position(&self, entity: Entity) -> Option { + let transform = self.blocks.get(entity).ok(); + transform.map(|t| t.translation.floor().as_ivec3()) + } } #[derive(Resource)] diff --git a/src/placement.rs b/src/placement.rs index 6ad4eb0..b603880 100644 --- a/src/placement.rs +++ b/src/placement.rs @@ -10,7 +10,6 @@ pub fn place_break_blocks( mouse_button_input: Res>, window: Single<(&Window, &CursorOptions)>, camera: Single<(&GlobalTransform, &Camera)>, - block_lookup: Query<&Transform, With>, ) { let (window, cursor) = window.into_inner(); let (cam_transform, camera) = camera.into_inner(); @@ -27,7 +26,7 @@ pub fn place_break_blocks( let Some((block, hit)) = ray_cast.cast_ray(ray, settings).first() else { return; // ray didn't hit anything }; - let Ok(block_transform) = block_lookup.get(*block) else { + let Some(block_pos) = blocks.position(*block) else { return; // entity hit is not a block }; @@ -36,9 +35,10 @@ pub fn place_break_blocks( commands.entity(*block).despawn(); } else if mouse_button_input.just_pressed(MouseButton::Right) { // Create a new block next to the one that was just clicked. - let pos = block_transform.translation.floor().as_ivec3(); + // FIXME: This only works for axis-aligned normals. let offset = hit.normal.normalize().round().as_ivec3(); - blocks.spawn(pos + offset); + + blocks.spawn(block_pos + offset); } }