Compare commits

..

5 Commits

Author SHA1 Message Date
copygirl a0e62c6d3a Refactor cursor grabbing and more 1 week ago
copygirl 957d3e962d Add block placement and breaking 1 week ago
copygirl b01f37fea4 Draw crosshair when cursor grabbed 1 week ago
copygirl 42460a76fb Use MeshRayCast to render debug ray 1 week ago
copygirl 69ae279f76 Rename CameraFreeLook variable to `look` 1 week ago
  1. BIN
      assets/crosshair.png
  2. 39
      src/block.rs
  3. 125
      src/camera.rs
  4. 63
      src/main.rs
  5. 48
      src/placement.rs

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 B

@ -0,0 +1,39 @@
use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
#[derive(Component)]
pub struct Block;
#[derive(SystemParam)]
pub struct Blocks<'w, 's> {
commands: Commands<'w, 's>,
block_resources: Res<'w, BlockResources>,
}
impl Blocks<'_, '_> {
pub fn spawn(&mut self, pos: IVec3) {
self.commands.spawn((
Block,
Mesh3d(self.block_resources.mesh.clone()),
MeshMaterial3d(self.block_resources.material.clone()),
Transform::from_translation(pos.as_vec3() + Vec3::ONE / 2.),
));
}
}
#[derive(Resource)]
pub struct BlockResources {
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
}
pub fn setup_blocks(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.insert_resource(BlockResources {
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
material: materials.add(Color::srgb_u8(124, 144, 255)),
});
}

@ -4,6 +4,53 @@ use bevy::input::mouse::AccumulatedMouseMotion;
use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions};
pub fn cursor_grab(
mut mouse_button_input: ResMut<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
window: Single<(&mut Window, &mut CursorOptions)>,
crosshair: Single<&mut Visibility, With<Crosshair>>,
mut request_center_cursor: Local<bool>,
) {
let (mut window, mut cursor) = window.into_inner();
let mut crosshair_visibility = crosshair.into_inner();
let is_grabbed = cursor.grab_mode == CursorGrabMode::Locked;
let request_grab = mouse_button_input.any_just_pressed([MouseButton::Left, MouseButton::Right]);
let request_ungrab = !window.focused || key_input.just_pressed(KeyCode::Escape);
if !is_grabbed && request_grab && !request_ungrab {
*crosshair_visibility = Visibility::Inherited;
cursor.grab_mode = CursorGrabMode::Locked;
cursor.visible = false;
// HACK: It appears setting the cursor position in the same frame we're
// locking it is not possible, so we're delaying it by a frame.
*request_center_cursor = true;
// To prevent other systems (such as `place_break_blocks`)
// from seeing the mouse button inputs, clear the state here.
mouse_button_input.clear();
}
if is_grabbed && *request_center_cursor {
// Set the cursor position to the middle of the window,
// so when it is ungrabbed again it'll reappear there.
let center = window.resolution.size() / 2.;
window.set_cursor_position(Some(center));
*request_center_cursor = false; // Only do this once.
}
if is_grabbed && request_ungrab && !request_grab {
*crosshair_visibility = Visibility::Hidden;
cursor.grab_mode = CursorGrabMode::None;
cursor.visible = true;
}
}
pub fn is_cursor_grabbed(cursor: Single<&CursorOptions>) -> bool {
cursor.grab_mode == CursorGrabMode::Locked
}
#[derive(Component, Debug)]
pub struct CameraFreeLook {
/// The mouse sensitivity, in radians per pixel.
@ -32,42 +79,27 @@ impl Default for CameraFreeLook {
}
}
pub fn camera_free_look(
window: Single<(&Window, &mut CursorOptions)>,
pub fn camera_look(
accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
camera: Single<(&mut Transform, &mut CameraFreeLook)>,
) {
let (window, mut cursor) = window.into_inner();
let (mut transform, mut camera) = camera.into_inner();
let (mut transform, mut look) = camera.into_inner();
if !window.focused || key_input.just_pressed(KeyCode::Escape) {
cursor.grab_mode = CursorGrabMode::None;
cursor.visible = true;
// Ensure the yaw and pitch are initialized once
// from the camera transform's current rotation.
if !look.initialized {
(look.yaw, look.pitch, _) = transform.rotation.to_euler(EulerRot::YXZ);
look.initialized = true;
}
if mouse_button_input.any_just_pressed([MouseButton::Left, MouseButton::Right]) {
cursor.grab_mode = CursorGrabMode::Locked;
cursor.visible = false;
}
if cursor.grab_mode == CursorGrabMode::Locked {
// Ensure the yaw and pitch are initialized once
// from the camera transform's current rotation.
if !camera.initialized {
(camera.yaw, camera.pitch, _) = transform.rotation.to_euler(EulerRot::YXZ);
camera.initialized = true;
}
// Update the current camera state's internal yaw and pitch.
let motion = accumulated_mouse_motion.delta * camera.sensitivity;
let (min, max) = camera.pitch_limit.clone().into_inner();
camera.yaw = (camera.yaw - motion.x).rem_euclid(TAU); // keep within 0°..360°
camera.pitch = (camera.pitch - motion.y).clamp(min, max);
// Update the current camera state's internal yaw and pitch.
let motion = accumulated_mouse_motion.delta * look.sensitivity;
let (min, max) = look.pitch_limit.clone().into_inner();
look.yaw = (look.yaw - motion.x).rem_euclid(TAU); // keep within 0°..360°
look.pitch = (look.pitch - motion.y).clamp(min, max);
// Override the camera transform's rotation.
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, camera.yaw, camera.pitch);
}
// Override the camera transform's rotation.
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, look.yaw, look.pitch);
}
// TODO: Make it possible to attach this to any entity, such as the player,
@ -109,14 +141,10 @@ impl Default for CameraNoClip {
pub fn noclip_controller(
time: Res<Time<Real>>,
cursor: Single<&mut CursorOptions>,
key_input: Res<ButtonInput<KeyCode>>,
camera: Single<(&mut Transform, &mut CameraNoClip)>,
camera: Single<(&mut Transform, &CameraNoClip)>,
) {
let (mut transform, noclip) = camera.into_inner();
if cursor.grab_mode != CursorGrabMode::Locked {
return;
}
#[rustfmt::skip]
let movement = {
@ -139,3 +167,32 @@ pub fn noclip_controller(
transform.translation += movement.z * dt * forward;
}
}
#[derive(Component)]
pub struct Crosshair;
pub fn setup_crosshair(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((
Node {
width: percent(100),
height: percent(100),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
children![(
Crosshair,
Node {
width: px(64),
height: px(64),
..default()
},
ImageNode {
image: asset_server.load("crosshair.png"),
..default()
},
// Hidden by default, because cursor shouldn't be grabbed at startup either.
Visibility::Hidden,
)],
));
}

@ -1,34 +1,43 @@
use bevy::prelude::*;
mod free_camera;
use free_camera::*;
mod block;
mod camera;
mod placement;
use block::*;
use camera::*;
use placement::*;
fn main() {
#[rustfmt::skip]
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, (camera_free_look, noclip_controller).chain())
.add_systems(Startup, setup_crosshair)
.add_systems(Startup, setup_blocks)
.add_systems(Startup, setup_scene.after(setup_blocks))
.add_systems(Update, cursor_grab)
.add_systems(Update, camera_look.after(cursor_grab).run_if(is_cursor_grabbed))
.add_systems(Update, noclip_controller.after(camera_look).run_if(is_cursor_grabbed))
// This system requires the camera's `GlobalTransform`, so for
// a most up-to-date value, run it right after it's been updated.
.add_systems(PostUpdate, place_break_blocks.after(TransformSystems::Propagate))
.run();
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// circular base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
// cube
fn setup_scene(mut commands: Commands, mut blocks: Blocks) {
// light
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.5, 0.0),
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
CameraFreeLook::default(),
CameraNoClip::default(),
));
// light
// camera
commands.spawn((
PointLight {
shadows_enabled: true,
@ -36,11 +45,11 @@ fn setup(
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
CameraFreeLook::default(),
CameraNoClip::default(),
));
// blocks
for x in -8..8 {
for z in -8..8 {
blocks.spawn(IVec3::new(x, 0, z));
}
}
}

@ -0,0 +1,48 @@
use bevy::prelude::*;
use bevy::window::{CursorGrabMode, CursorOptions};
use crate::block::*;
pub fn place_break_blocks(
mut commands: Commands,
mut blocks: Blocks,
mut ray_cast: MeshRayCast,
mouse_button_input: Res<ButtonInput<MouseButton>>,
window: Single<(&Window, &CursorOptions)>,
camera: Single<(&GlobalTransform, &Camera)>,
block_lookup: Query<&Transform, With<Block>>,
) {
if !mouse_button_input.any_just_pressed([MouseButton::Left, MouseButton::Right]) {
return; // only run this system when left or right mouse button is pressed
}
let (window, cursor) = window.into_inner();
let (cam_transform, camera) = camera.into_inner();
let ray = if cursor.grab_mode == CursorGrabMode::Locked {
Ray3d::new(cam_transform.translation(), cam_transform.forward())
} else if let Some(cursor_pos) = window.cursor_position() {
camera.viewport_to_world(cam_transform, cursor_pos).unwrap()
} else {
return; // cursor outside window area
};
let settings = &MeshRayCastSettings::default();
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 {
return; // entity hit is not a block
};
if mouse_button_input.just_pressed(MouseButton::Left) {
// Destroy the block clicked.
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);
}
}
Loading…
Cancel
Save