Extract examples CameraController into a module (#11338)

# Objective

Unify flycam-style camera controller from the examples.

`parallax_mapping` controller was kept as is.

## Solution

Fixed some mouse movement & cursor grabbing related issues too.
This commit is contained in:
MiniaczQ 2024-01-14 14:50:33 +01:00 committed by GitHub
parent 6f6269e195
commit ec5b9eeba7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 244 additions and 459 deletions

View file

@ -1,12 +1,15 @@
//! Demonstrates how shadow biases affect shadows in a 3d scene. //! Demonstrates how shadow biases affect shadows in a 3d scene.
use std::f32::consts::PI; #[path = "../helpers/camera_controller.rs"]
mod camera_controller;
use bevy::{input::mouse::MouseMotion, pbr::ShadowFilteringMethod, prelude::*}; use bevy::{pbr::ShadowFilteringMethod, prelude::*};
use camera_controller::{CameraController, CameraControllerPlugin};
fn main() { fn main() {
App::new() App::new()
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins)
.add_plugins(CameraControllerPlugin)
.add_systems(Startup, setup) .add_systems(Startup, setup)
.add_systems( .add_systems(
Update, Update,
@ -16,7 +19,6 @@ fn main() {
adjust_point_light_biases, adjust_point_light_biases,
toggle_light, toggle_light,
adjust_directional_light_biases, adjust_directional_light_biases,
camera_controller,
), ),
) )
.run(); .run();
@ -135,8 +137,6 @@ fn setup(
.with_children(|c| { .with_children(|c| {
c.spawn(TextBundle::from_sections([ c.spawn(TextBundle::from_sections([
TextSection::new("Controls:\n", style.clone()), TextSection::new("Controls:\n", style.clone()),
TextSection::new("WSAD - forward/back/strafe left/right\n", style.clone()),
TextSection::new("E / Q - up / down\n", style.clone()),
TextSection::new("R / Z - reset biases to default / zero\n", style.clone()), TextSection::new("R / Z - reset biases to default / zero\n", style.clone()),
TextSection::new( TextSection::new(
"L - switch between directional and point lights [", "L - switch between directional and point lights [",
@ -195,7 +195,7 @@ fn toggle_light(
if input.just_pressed(KeyCode::KeyL) { if input.just_pressed(KeyCode::KeyL) {
for mut light in &mut point_lights { for mut light in &mut point_lights {
light.intensity = if light.intensity == 0.0 { light.intensity = if light.intensity == 0.0 {
example_text.single_mut().sections[5].value = "PointLight".to_string(); example_text.single_mut().sections[3].value = "PointLight".to_string();
100000000.0 100000000.0
} else { } else {
0.0 0.0
@ -203,7 +203,7 @@ fn toggle_light(
} }
for mut light in &mut directional_lights { for mut light in &mut directional_lights {
light.illuminance = if light.illuminance == 0.0 { light.illuminance = if light.illuminance == 0.0 {
example_text.single_mut().sections[5].value = "DirectionalLight".to_string(); example_text.single_mut().sections[3].value = "DirectionalLight".to_string();
100000.0 100000.0
} else { } else {
0.0 0.0
@ -241,9 +241,9 @@ fn adjust_light_position(
for mut light in &mut lights { for mut light in &mut lights {
light.translation += offset; light.translation += offset;
light.look_at(Vec3::ZERO, Vec3::Y); light.look_at(Vec3::ZERO, Vec3::Y);
example_text.sections[23].value = format!("{:.1},", light.translation.x); example_text.sections[21].value = format!("{:.1},", light.translation.x);
example_text.sections[24].value = format!(" {:.1},", light.translation.y); example_text.sections[22].value = format!(" {:.1},", light.translation.y);
example_text.sections[25].value = format!(" {:.1}", light.translation.z); example_text.sections[23].value = format!(" {:.1}", light.translation.z);
} }
} }
} }
@ -270,7 +270,7 @@ fn cycle_filter_methods(
ShadowFilteringMethod::Hardware2x2 ShadowFilteringMethod::Hardware2x2
} }
}; };
example_text.single_mut().sections[8].value = filter_method_string; example_text.single_mut().sections[6].value = filter_method_string;
} }
} }
} }
@ -304,8 +304,8 @@ fn adjust_point_light_biases(
light.shadow_normal_bias = 0.0; light.shadow_normal_bias = 0.0;
} }
example_text.single_mut().sections[11].value = format!("{:.2}", light.shadow_depth_bias); example_text.single_mut().sections[9].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[14].value = format!("{:.1}", light.shadow_normal_bias); example_text.single_mut().sections[12].value = format!("{:.1}", light.shadow_normal_bias);
} }
} }
@ -338,119 +338,7 @@ fn adjust_directional_light_biases(
light.shadow_normal_bias = 0.0; light.shadow_normal_bias = 0.0;
} }
example_text.single_mut().sections[17].value = format!("{:.2}", light.shadow_depth_bias); example_text.single_mut().sections[15].value = format!("{:.2}", light.shadow_depth_bias);
example_text.single_mut().sections[20].value = format!("{:.1}", light.shadow_normal_bias); example_text.single_mut().sections[18].value = format!("{:.1}", light.shadow_normal_bias);
}
}
#[derive(Component)]
struct CameraController {
pub enabled: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}
impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
sensitivity: 0.5,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
walk_speed: 10.0,
run_speed: 30.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}
fn camera_controller(
time: Res<Time>,
mut mouse_events: EventReader<MouseMotion>,
key_input: Res<ButtonInput<KeyCode>>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
for (mut transform, mut options) in &mut query {
if !options.enabled {
continue;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(options.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(options.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(options.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(options.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(options.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(options.key_down) {
axis_input.y -= 1.0;
}
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(options.key_run) {
options.run_speed
} else {
options.walk_speed
};
options.velocity = axis_input.normalize() * max_speed;
} else {
let friction = options.friction.clamp(0.0, 1.0);
options.velocity *= 1.0 - friction;
if options.velocity.length_squared() < 1e-6 {
options.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += options.velocity.x * dt * right
+ options.velocity.y * dt * Vec3::Y
+ options.velocity.z * dt * forward;
if mouse_delta != Vec2::ZERO {
// Apply look update
options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
.clamp(-PI / 2., PI / 2.);
options.yaw -= mouse_delta.x * options.sensitivity * dt;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
}
} }
} }

View file

@ -1,9 +1,11 @@
//! Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats //! Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats
#[path = "../helpers/camera_controller.rs"]
mod camera_controller;
use bevy::{ use bevy::{
asset::LoadState, asset::LoadState,
core_pipeline::Skybox, core_pipeline::Skybox,
input::mouse::MouseMotion,
prelude::*, prelude::*,
render::{ render::{
render_resource::{TextureViewDescriptor, TextureViewDimension}, render_resource::{TextureViewDescriptor, TextureViewDimension},
@ -11,6 +13,7 @@ use bevy::{
texture::CompressedImageFormats, texture::CompressedImageFormats,
}, },
}; };
use camera_controller::{CameraController, CameraControllerPlugin};
use std::f32::consts::PI; use std::f32::consts::PI;
const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[ const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[
@ -35,13 +38,13 @@ const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[
fn main() { fn main() {
App::new() App::new()
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins)
.add_plugins(CameraControllerPlugin)
.add_systems(Startup, setup) .add_systems(Startup, setup)
.add_systems( .add_systems(
Update, Update,
( (
cycle_cubemap_asset, cycle_cubemap_asset,
asset_loaded.after(cycle_cubemap_asset), asset_loaded.after(cycle_cubemap_asset),
camera_controller,
animate_light_direction, animate_light_direction,
), ),
) )
@ -169,134 +172,3 @@ fn animate_light_direction(
transform.rotate_y(time.delta_seconds() * 0.5); transform.rotate_y(time.delta_seconds() * 0.5);
} }
} }
#[derive(Component)]
pub struct CameraController {
pub enabled: bool,
pub initialized: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub mouse_key_enable_mouse: MouseButton,
pub keyboard_key_enable_mouse: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}
impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
initialized: false,
sensitivity: 0.5,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
mouse_key_enable_mouse: MouseButton::Left,
keyboard_key_enable_mouse: KeyCode::KeyM,
walk_speed: 2.0,
run_speed: 6.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}
pub fn camera_controller(
time: Res<Time>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut move_toggled: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut options)) = query.get_single_mut() {
if !options.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
options.yaw = yaw;
options.pitch = pitch;
options.initialized = true;
}
if !options.enabled {
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(options.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(options.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(options.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(options.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(options.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(options.key_down) {
axis_input.y -= 1.0;
}
if key_input.just_pressed(options.keyboard_key_enable_mouse) {
*move_toggled = !*move_toggled;
}
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(options.key_run) {
options.run_speed
} else {
options.walk_speed
};
options.velocity = axis_input.normalize() * max_speed;
} else {
let friction = options.friction.clamp(0.0, 1.0);
options.velocity *= 1.0 - friction;
if options.velocity.length_squared() < 1e-6 {
options.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += options.velocity.x * dt * right
+ options.velocity.y * dt * Vec3::Y
+ options.velocity.z * dt * forward;
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if mouse_button_input.pressed(options.mouse_key_enable_mouse) || *move_toggled {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
}
if mouse_delta != Vec2::ZERO {
// Apply look update
options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
.clamp(-PI / 2., PI / 2.);
options.yaw -= mouse_delta.x * options.sensitivity * dt;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
}
}
}

View file

@ -0,0 +1,219 @@
//! A freecam-style camera controller plugin.
//! To use in your own application:
//! - Copy the code for the [`CameraControllerPlugin`] and add the plugin to your App.
//! - Attach the [`CameraController`] component to an entity with a [`Camera3dBundle`].
use bevy::input::mouse::MouseMotion;
use bevy::prelude::*;
use bevy::window::CursorGrabMode;
use std::{f32::consts::*, fmt};
pub struct CameraControllerPlugin;
impl Plugin for CameraControllerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, run_camera_controller);
}
}
/// Based on Valorant's default sensitivity, not entirely sure why it is exactly 1.0 / 180.0,
/// but I'm guessing it is a misunderstanding between degrees/radians and then sticking with
/// it because it felt nice.
pub const RADIANS_PER_DOT: f32 = 1.0 / 180.0;
#[derive(Component)]
pub struct CameraController {
pub enabled: bool,
pub initialized: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub mouse_key_cursor_grab: MouseButton,
pub keyboard_key_toggle_cursor_grab: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}
impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
initialized: false,
sensitivity: 1.0,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
mouse_key_cursor_grab: MouseButton::Left,
keyboard_key_toggle_cursor_grab: KeyCode::KeyM,
walk_speed: 5.0,
run_speed: 15.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}
impl fmt::Display for CameraController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"
Freecam Controls:
Mouse\t- Move camera orientation
{:?}\t- Hold to grab cursor
{:?}\t- Toggle cursor grab
{:?} & {:?}\t- Fly forward & backwards
{:?} & {:?}\t- Fly sideways left & right
{:?} & {:?}\t- Fly up & down
{:?}\t- Fly faster while held",
self.mouse_key_cursor_grab,
self.keyboard_key_toggle_cursor_grab,
self.key_forward,
self.key_back,
self.key_left,
self.key_right,
self.key_up,
self.key_down,
self.key_run,
)
}
}
#[allow(clippy::too_many_arguments)]
fn run_camera_controller(
time: Res<Time>,
mut windows: Query<&mut Window>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut toggle_cursor_grab: Local<bool>,
mut mouse_cursor_grab: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut controller)) = query.get_single_mut() {
if !controller.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
controller.yaw = yaw;
controller.pitch = pitch;
controller.initialized = true;
info!("{}", *controller);
}
if !controller.enabled {
mouse_events.clear();
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(controller.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(controller.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(controller.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(controller.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(controller.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(controller.key_down) {
axis_input.y -= 1.0;
}
let mut cursor_grab_change = false;
if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
*toggle_cursor_grab = !*toggle_cursor_grab;
cursor_grab_change = true;
}
if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = true;
cursor_grab_change = true;
}
if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
*mouse_cursor_grab = false;
cursor_grab_change = true;
}
let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(controller.key_run) {
controller.run_speed
} else {
controller.walk_speed
};
controller.velocity = axis_input.normalize() * max_speed;
} else {
let friction = controller.friction.clamp(0.0, 1.0);
controller.velocity *= 1.0 - friction;
if controller.velocity.length_squared() < 1e-6 {
controller.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += controller.velocity.x * dt * right
+ controller.velocity.y * dt * Vec3::Y
+ controller.velocity.z * dt * forward;
// Handle cursor grab
if cursor_grab_change {
if cursor_grab {
for mut window in &mut windows {
if !window.focused {
continue;
}
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
} else {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
}
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if cursor_grab {
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
} else {
mouse_events.clear();
}
if mouse_delta != Vec2::ZERO {
// Apply look update
controller.pitch = (controller.pitch
- mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
.clamp(-PI / 2., PI / 2.);
controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
transform.rotation =
Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
}
}
}

View file

@ -1,196 +0,0 @@
//! A freecam-style camera controller plugin.
//! To use in your own application:
//! - Copy the code for the [`CameraControllerPlugin`] and add the plugin to your App.
//! - Attach the [`CameraController`] component to an entity with a [`Camera3dBundle`].
use bevy::window::CursorGrabMode;
use bevy::{input::mouse::MouseMotion, prelude::*};
use std::f32::consts::*;
use std::fmt;
/// Based on Valorant's default sensitivity, not entirely sure why it is exactly 1.0 / 180.0,
/// but I'm guessing it is a misunderstanding between degrees/radians and then sticking with
/// it because it felt nice.
pub const RADIANS_PER_DOT: f32 = 1.0 / 180.0;
#[derive(Component)]
pub struct CameraController {
pub enabled: bool,
pub initialized: bool,
pub sensitivity: f32,
pub key_forward: KeyCode,
pub key_back: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub key_run: KeyCode,
pub mouse_key_enable_mouse: MouseButton,
pub keyboard_key_enable_mouse: KeyCode,
pub walk_speed: f32,
pub run_speed: f32,
pub friction: f32,
pub pitch: f32,
pub yaw: f32,
pub velocity: Vec3,
}
impl Default for CameraController {
fn default() -> Self {
Self {
enabled: true,
initialized: false,
sensitivity: 1.0,
key_forward: KeyCode::KeyW,
key_back: KeyCode::KeyS,
key_left: KeyCode::KeyA,
key_right: KeyCode::KeyD,
key_up: KeyCode::KeyE,
key_down: KeyCode::KeyQ,
key_run: KeyCode::ShiftLeft,
mouse_key_enable_mouse: MouseButton::Left,
keyboard_key_enable_mouse: KeyCode::KeyM,
walk_speed: 5.0,
run_speed: 15.0,
friction: 0.5,
pitch: 0.0,
yaw: 0.0,
velocity: Vec3::ZERO,
}
}
}
impl fmt::Display for CameraController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"
Freecam Controls:
MOUSE\t- Move camera orientation
{:?}/{:?}\t- Enable mouse movement
{:?}{:?}\t- forward/backward
{:?}{:?}\t- strafe left/right
{:?}\t- 'run'
{:?}\t- up
{:?}\t- down",
self.mouse_key_enable_mouse,
self.keyboard_key_enable_mouse,
self.key_forward,
self.key_back,
self.key_left,
self.key_right,
self.key_run,
self.key_up,
self.key_down
)
}
}
pub struct CameraControllerPlugin;
impl Plugin for CameraControllerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, camera_controller);
}
}
fn camera_controller(
time: Res<Time>,
mut windows: Query<&mut Window>,
mut mouse_events: EventReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
key_input: Res<ButtonInput<KeyCode>>,
mut move_toggled: Local<bool>,
mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
let dt = time.delta_seconds();
if let Ok((mut transform, mut options)) = query.get_single_mut() {
if !options.initialized {
let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
options.yaw = yaw;
options.pitch = pitch;
options.initialized = true;
}
if !options.enabled {
return;
}
// Handle key input
let mut axis_input = Vec3::ZERO;
if key_input.pressed(options.key_forward) {
axis_input.z += 1.0;
}
if key_input.pressed(options.key_back) {
axis_input.z -= 1.0;
}
if key_input.pressed(options.key_right) {
axis_input.x += 1.0;
}
if key_input.pressed(options.key_left) {
axis_input.x -= 1.0;
}
if key_input.pressed(options.key_up) {
axis_input.y += 1.0;
}
if key_input.pressed(options.key_down) {
axis_input.y -= 1.0;
}
if key_input.just_pressed(options.keyboard_key_enable_mouse) {
*move_toggled = !*move_toggled;
}
// Apply movement update
if axis_input != Vec3::ZERO {
let max_speed = if key_input.pressed(options.key_run) {
options.run_speed
} else {
options.walk_speed
};
options.velocity = axis_input.normalize() * max_speed;
} else {
let friction = options.friction.clamp(0.0, 1.0);
options.velocity *= 1.0 - friction;
if options.velocity.length_squared() < 1e-6 {
options.velocity = Vec3::ZERO;
}
}
let forward = transform.forward();
let right = transform.right();
transform.translation += options.velocity.x * dt * right
+ options.velocity.y * dt * Vec3::Y
+ options.velocity.z * dt * forward;
// Handle mouse input
let mut mouse_delta = Vec2::ZERO;
if mouse_button_input.pressed(options.mouse_key_enable_mouse) || *move_toggled {
for mut window in &mut windows {
if !window.focused {
continue;
}
window.cursor.grab_mode = CursorGrabMode::Locked;
window.cursor.visible = false;
}
for mouse_event in mouse_events.read() {
mouse_delta += mouse_event.delta;
}
}
if mouse_button_input.just_released(options.mouse_key_enable_mouse) {
for mut window in &mut windows {
window.cursor.grab_mode = CursorGrabMode::None;
window.cursor.visible = true;
}
}
if mouse_delta != Vec2::ZERO {
// Apply look update
options.pitch = (options.pitch - mouse_delta.y * RADIANS_PER_DOT * options.sensitivity)
.clamp(-PI / 2., PI / 2.);
options.yaw -= mouse_delta.x * RADIANS_PER_DOT * options.sensitivity;
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
}
}
}

View file

@ -14,13 +14,15 @@ use bevy::{
window::WindowPlugin, window::WindowPlugin,
}; };
#[path = "../../helpers/camera_controller.rs"]
mod camera_controller;
#[cfg(feature = "animation")] #[cfg(feature = "animation")]
mod animation_plugin; mod animation_plugin;
mod camera_controller_plugin;
mod morph_viewer_plugin; mod morph_viewer_plugin;
mod scene_viewer_plugin; mod scene_viewer_plugin;
use camera_controller_plugin::{CameraController, CameraControllerPlugin}; use camera_controller::{CameraController, CameraControllerPlugin};
use morph_viewer_plugin::MorphViewerPlugin; use morph_viewer_plugin::MorphViewerPlugin;
use scene_viewer_plugin::{SceneHandle, SceneViewerPlugin}; use scene_viewer_plugin::{SceneHandle, SceneViewerPlugin};

View file

@ -11,7 +11,7 @@ use bevy::{
use std::f32::consts::*; use std::f32::consts::*;
use std::fmt; use std::fmt;
use super::camera_controller_plugin::*; use super::camera_controller::*;
#[derive(Resource)] #[derive(Resource)]
pub struct SceneHandle { pub struct SceneHandle {