Add `Blocks.position` function

main
copygirl 6 days ago
parent fac93b94c9
commit 209576bc18
  1. 8
      src/block.rs
  2. 8
      src/placement.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<Block>>,
}
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<IVec3> {
let transform = self.blocks.get(entity).ok();
transform.map(|t| t.translation.floor().as_ivec3())
}
}
#[derive(Resource)]

@ -10,7 +10,6 @@ pub fn place_break_blocks(
mouse_button_input: Res<ButtonInput<MouseButton>>,
window: Single<(&Window, &CursorOptions)>,
camera: Single<(&GlobalTransform, &Camera)>,
block_lookup: Query<&Transform, With<Block>>,
) {
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);
}
}

Loading…
Cancel
Save