move clientside gated parts of control to the client (#70)
This commit is contained in:
348
crates/client/src/control/controls.rs
Normal file
348
crates/client/src/control/controls.rs
Normal file
@@ -0,0 +1,348 @@
|
||||
use super::Controls;
|
||||
use crate::{GameState, control::CharacterInputEnabled};
|
||||
use bevy::input::{
|
||||
ButtonState,
|
||||
gamepad::{GamepadConnection, GamepadEvent},
|
||||
mouse::{MouseButtonInput, MouseMotion},
|
||||
};
|
||||
use bevy::prelude::*;
|
||||
use lightyear::input::client::InputSet;
|
||||
use lightyear::prelude::input::native::{ActionState, InputMarker};
|
||||
use shared::control::{ControlState, ControllerSet};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
pub fn plugin(app: &mut App) {
|
||||
app.init_resource::<Controls>();
|
||||
app.init_resource::<InputStateCache<KeyCode>>();
|
||||
|
||||
app.register_required_components::<Gamepad, InputStateCache<GamepadButton>>();
|
||||
|
||||
app.add_systems(PreUpdate, (cache_keyboard_state, cache_gamepad_state));
|
||||
|
||||
app.add_systems(
|
||||
FixedPreUpdate,
|
||||
(
|
||||
gamepad_controls,
|
||||
keyboard_controls,
|
||||
mouse_rotate,
|
||||
mouse_click,
|
||||
gamepad_connections.run_if(on_event::<GamepadEvent>),
|
||||
combine_controls,
|
||||
clear_keyboard_state,
|
||||
clear_gamepad_state,
|
||||
)
|
||||
.chain()
|
||||
.in_set(ControllerSet::CollectInputs)
|
||||
.before(InputSet::WriteClientInputs)
|
||||
.run_if(
|
||||
in_state(GameState::Playing)
|
||||
.and(resource_exists_and_equals(CharacterInputEnabled::On)),
|
||||
),
|
||||
)
|
||||
.add_systems(
|
||||
FixedPreUpdate,
|
||||
buffer_inputs.in_set(InputSet::WriteClientInputs),
|
||||
);
|
||||
|
||||
app.add_systems(
|
||||
Update,
|
||||
reset_control_state_on_disable.run_if(in_state(GameState::Playing)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Write inputs from combined keyboard/gamepad state into the networked input buffer
|
||||
/// for the local player.
|
||||
fn buffer_inputs(
|
||||
mut player: Single<&mut ActionState<ControlState>, With<InputMarker<ControlState>>>,
|
||||
controls: Res<ControlState>,
|
||||
) {
|
||||
player.0 = *controls;
|
||||
}
|
||||
|
||||
/// Reset character inputs to default when character input is disabled.
|
||||
fn reset_control_state_on_disable(
|
||||
state: Res<CharacterInputEnabled>,
|
||||
mut controls: ResMut<Controls>,
|
||||
mut control_state: ResMut<ControlState>,
|
||||
) {
|
||||
if state.is_changed() && matches!(*state, CharacterInputEnabled::Off) {
|
||||
*controls = Controls::default();
|
||||
*control_state = ControlState::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// Caches information that depends on the Update schedule so that it can be read safely from the Fixed schedule
|
||||
/// without losing/duplicating info
|
||||
#[derive(Component, Resource)]
|
||||
struct InputStateCache<Button> {
|
||||
map: HashMap<Button, InputState>,
|
||||
}
|
||||
|
||||
impl<Button> Default for InputStateCache<Button> {
|
||||
fn default() -> Self {
|
||||
Self { map: default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Button: Hash + Eq> InputStateCache<Button> {
|
||||
fn clear(&mut self) {
|
||||
for state in self.map.values_mut() {
|
||||
*state = InputState::default();
|
||||
}
|
||||
}
|
||||
|
||||
fn pressed(&self, button: Button) -> bool {
|
||||
self.map
|
||||
.get(&button)
|
||||
.map(|state| state.pressed)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn just_pressed(&self, button: Button) -> bool {
|
||||
self.map
|
||||
.get(&button)
|
||||
.map(|state| state.just_pressed)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct InputState {
|
||||
pressed: bool,
|
||||
just_pressed: bool,
|
||||
}
|
||||
|
||||
fn cache_keyboard_state(
|
||||
mut cache: ResMut<InputStateCache<KeyCode>>,
|
||||
keyboard: Res<ButtonInput<KeyCode>>,
|
||||
) {
|
||||
let mut cache_key = |key| {
|
||||
cache.map.entry(key).or_default().pressed |= keyboard.pressed(key);
|
||||
cache.map.entry(key).or_default().just_pressed |= keyboard.just_pressed(key);
|
||||
};
|
||||
cache_key(KeyCode::Space);
|
||||
cache_key(KeyCode::Tab);
|
||||
cache_key(KeyCode::KeyB);
|
||||
cache_key(KeyCode::Enter);
|
||||
cache_key(KeyCode::Comma);
|
||||
cache_key(KeyCode::Period);
|
||||
cache_key(KeyCode::KeyQ);
|
||||
cache_key(KeyCode::KeyE);
|
||||
}
|
||||
|
||||
fn clear_keyboard_state(mut cache: ResMut<InputStateCache<KeyCode>>) {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
fn cache_gamepad_state(mut gamepads: Query<(&Gamepad, &mut InputStateCache<GamepadButton>)>) {
|
||||
for (gamepad, mut cache) in gamepads.iter_mut() {
|
||||
let mut cache_button = |button| {
|
||||
cache.map.entry(button).or_default().pressed |= gamepad.pressed(button);
|
||||
cache.map.entry(button).or_default().just_pressed |= gamepad.just_pressed(button);
|
||||
};
|
||||
|
||||
cache_button(GamepadButton::North);
|
||||
cache_button(GamepadButton::East);
|
||||
cache_button(GamepadButton::South);
|
||||
cache_button(GamepadButton::West);
|
||||
cache_button(GamepadButton::DPadUp);
|
||||
cache_button(GamepadButton::DPadRight);
|
||||
cache_button(GamepadButton::DPadDown);
|
||||
cache_button(GamepadButton::DPadLeft);
|
||||
cache_button(GamepadButton::LeftTrigger);
|
||||
cache_button(GamepadButton::LeftTrigger2);
|
||||
cache_button(GamepadButton::RightTrigger);
|
||||
cache_button(GamepadButton::RightTrigger2);
|
||||
cache_button(GamepadButton::Select);
|
||||
cache_button(GamepadButton::Start);
|
||||
cache_button(GamepadButton::LeftThumb);
|
||||
cache_button(GamepadButton::RightThumb);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_gamepad_state(mut caches: Query<&mut InputStateCache<GamepadButton>>) {
|
||||
for mut cache in caches.iter_mut() {
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Take keyboard and gamepad state and combine them into unified input state
|
||||
fn combine_controls(controls: Res<Controls>, mut combined_controls: ResMut<ControlState>) {
|
||||
let keyboard = controls.keyboard_state;
|
||||
let gamepad = controls.gamepad_state.unwrap_or_default();
|
||||
|
||||
combined_controls.look_dir = gamepad.look_dir + keyboard.look_dir;
|
||||
combined_controls.move_dir = gamepad.move_dir + keyboard.move_dir;
|
||||
combined_controls.jump = gamepad.jump | keyboard.jump;
|
||||
combined_controls.view_mode = gamepad.view_mode | keyboard.view_mode;
|
||||
combined_controls.trigger = keyboard.trigger | gamepad.trigger;
|
||||
combined_controls.just_triggered = keyboard.just_triggered | gamepad.just_triggered;
|
||||
combined_controls.select_left = gamepad.select_left | keyboard.select_left;
|
||||
combined_controls.select_right = gamepad.select_right | keyboard.select_right;
|
||||
combined_controls.backpack_toggle = gamepad.backpack_toggle | keyboard.backpack_toggle;
|
||||
combined_controls.backpack_swap = gamepad.backpack_swap | keyboard.backpack_swap;
|
||||
combined_controls.backpack_left = gamepad.backpack_left | keyboard.backpack_left;
|
||||
combined_controls.backpack_right = gamepad.backpack_right | keyboard.backpack_right;
|
||||
combined_controls.cash_heal = gamepad.cash_heal | keyboard.cash_heal;
|
||||
}
|
||||
|
||||
/// Applies a square deadzone to a Vec2
|
||||
fn deadzone_square(v: Vec2, min: f32) -> Vec2 {
|
||||
Vec2::new(
|
||||
if v.x.abs() < min { 0. } else { v.x },
|
||||
if v.y.abs() < min { 0. } else { v.y },
|
||||
)
|
||||
}
|
||||
|
||||
/// Collect gamepad inputs
|
||||
fn gamepad_controls(
|
||||
gamepads: Query<(Entity, &Gamepad, &InputStateCache<GamepadButton>)>,
|
||||
mut controls: ResMut<Controls>,
|
||||
) {
|
||||
let Some((_e, gamepad, cache)) = gamepads.iter().next() else {
|
||||
if controls.gamepad_state.is_some() {
|
||||
controls.gamepad_state = None;
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
let deadzone_left_stick = 0.15;
|
||||
let deadzone_right_stick = 0.15;
|
||||
|
||||
let rotate = gamepad
|
||||
.get(GamepadButton::RightTrigger2)
|
||||
.unwrap_or_default();
|
||||
|
||||
// 8BitDo Ultimate wireless Controller for PC
|
||||
let look_dir = if gamepad.vendor_id() == Some(11720) && gamepad.product_id() == Some(12306) {
|
||||
const EPSILON: f32 = 0.015;
|
||||
Vec2::new(
|
||||
if rotate < 0.5 - EPSILON {
|
||||
40. * (rotate - 0.5)
|
||||
} else if rotate > 0.5 + EPSILON {
|
||||
-40. * (rotate - 0.5)
|
||||
} else {
|
||||
0.
|
||||
},
|
||||
0.,
|
||||
)
|
||||
} else {
|
||||
deadzone_square(gamepad.right_stick(), deadzone_right_stick) * 40.
|
||||
};
|
||||
|
||||
let state = ControlState {
|
||||
move_dir: deadzone_square(gamepad.left_stick(), deadzone_left_stick),
|
||||
look_dir,
|
||||
jump: cache.pressed(GamepadButton::South),
|
||||
view_mode: cache.pressed(GamepadButton::LeftTrigger2),
|
||||
trigger: cache.pressed(GamepadButton::RightTrigger2),
|
||||
just_triggered: cache.just_pressed(GamepadButton::RightTrigger2),
|
||||
select_left: cache.just_pressed(GamepadButton::LeftTrigger),
|
||||
select_right: cache.just_pressed(GamepadButton::RightTrigger),
|
||||
backpack_left: cache.just_pressed(GamepadButton::DPadLeft),
|
||||
backpack_right: cache.just_pressed(GamepadButton::DPadRight),
|
||||
backpack_swap: cache.just_pressed(GamepadButton::DPadDown),
|
||||
backpack_toggle: cache.just_pressed(GamepadButton::DPadUp),
|
||||
cash_heal: cache.just_pressed(GamepadButton::East),
|
||||
};
|
||||
|
||||
if controls
|
||||
.gamepad_state
|
||||
.as_ref()
|
||||
.map(|last_state| *last_state != state)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
controls.gamepad_state = Some(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect mouse movement input
|
||||
fn mouse_rotate(mut mouse: EventReader<MouseMotion>, mut controls: ResMut<Controls>) {
|
||||
controls.keyboard_state.look_dir = Vec2::ZERO;
|
||||
|
||||
for ev in mouse.read() {
|
||||
controls.keyboard_state.look_dir += ev.delta;
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect keyboard input
|
||||
fn keyboard_controls(
|
||||
keyboard: Res<ButtonInput<KeyCode>>,
|
||||
cache: Res<InputStateCache<KeyCode>>,
|
||||
mut controls: ResMut<Controls>,
|
||||
) {
|
||||
let up_binds = [KeyCode::KeyW, KeyCode::ArrowUp];
|
||||
let down_binds = [KeyCode::KeyS, KeyCode::ArrowDown];
|
||||
let left_binds = [KeyCode::KeyA, KeyCode::ArrowLeft];
|
||||
let right_binds = [KeyCode::KeyD, KeyCode::ArrowRight];
|
||||
|
||||
let up = keyboard.any_pressed(up_binds);
|
||||
let down = keyboard.any_pressed(down_binds);
|
||||
let left = keyboard.any_pressed(left_binds);
|
||||
let right = keyboard.any_pressed(right_binds);
|
||||
|
||||
let horizontal = right as i8 - left as i8;
|
||||
let vertical = up as i8 - down as i8;
|
||||
let direction = Vec2::new(horizontal as f32, vertical as f32).clamp_length_max(1.0);
|
||||
|
||||
controls.keyboard_state.move_dir = direction;
|
||||
controls.keyboard_state.jump = cache.pressed(KeyCode::Space);
|
||||
controls.keyboard_state.view_mode = cache.pressed(KeyCode::Tab);
|
||||
controls.keyboard_state.backpack_toggle = cache.just_pressed(KeyCode::KeyB);
|
||||
controls.keyboard_state.backpack_swap = cache.just_pressed(KeyCode::Enter);
|
||||
controls.keyboard_state.backpack_left = cache.just_pressed(KeyCode::Comma);
|
||||
controls.keyboard_state.backpack_right = cache.just_pressed(KeyCode::Period);
|
||||
controls.keyboard_state.select_left = cache.just_pressed(KeyCode::KeyQ);
|
||||
controls.keyboard_state.select_right = cache.just_pressed(KeyCode::KeyE);
|
||||
controls.keyboard_state.cash_heal = cache.just_pressed(KeyCode::Enter);
|
||||
}
|
||||
|
||||
/// Collect mouse button input when pressed
|
||||
fn mouse_click(mut events: EventReader<MouseButtonInput>, mut controls: ResMut<Controls>) {
|
||||
controls.keyboard_state.just_triggered = false;
|
||||
|
||||
for ev in events.read() {
|
||||
match ev {
|
||||
MouseButtonInput {
|
||||
button: MouseButton::Left,
|
||||
state: ButtonState::Pressed,
|
||||
..
|
||||
} => {
|
||||
controls.keyboard_state.trigger = true;
|
||||
controls.keyboard_state.just_triggered = true;
|
||||
}
|
||||
MouseButtonInput {
|
||||
button: MouseButton::Left,
|
||||
state: ButtonState::Released,
|
||||
..
|
||||
} => {
|
||||
controls.keyboard_state.trigger = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive gamepad connections and disconnections
|
||||
fn gamepad_connections(mut evr_gamepad: EventReader<GamepadEvent>) {
|
||||
for ev in evr_gamepad.read() {
|
||||
if let GamepadEvent::Connection(connection) = ev {
|
||||
match &connection.connection {
|
||||
GamepadConnection::Connected {
|
||||
name,
|
||||
vendor_id,
|
||||
product_id,
|
||||
} => {
|
||||
info!(
|
||||
"New gamepad connected: {:?}, name: {name}, vendor: {vendor_id:?}, product: {product_id:?}",
|
||||
connection.gamepad,
|
||||
);
|
||||
}
|
||||
GamepadConnection::Disconnected => {
|
||||
info!("Lost connection with gamepad: {:?}", connection.gamepad);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
28
crates/client/src/control/mod.rs
Normal file
28
crates/client/src/control/mod.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use crate::GameState;
|
||||
use bevy::prelude::*;
|
||||
use shared::control::{ControlState, ControllerSet};
|
||||
|
||||
pub mod controls;
|
||||
|
||||
#[derive(Resource, Debug, Default)]
|
||||
struct Controls {
|
||||
keyboard_state: ControlState,
|
||||
gamepad_state: Option<ControlState>,
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, PartialEq, Eq)]
|
||||
pub enum CharacterInputEnabled {
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
|
||||
pub fn plugin(app: &mut App) {
|
||||
app.insert_resource(CharacterInputEnabled::On);
|
||||
|
||||
app.add_plugins(controls::plugin);
|
||||
|
||||
app.configure_sets(
|
||||
FixedPreUpdate,
|
||||
ControllerSet::CollectInputs.run_if(in_state(GameState::Playing)),
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
mod backpack;
|
||||
mod client;
|
||||
mod control;
|
||||
mod debug;
|
||||
mod enemy;
|
||||
mod heal_effect;
|
||||
@@ -124,6 +125,7 @@ fn main() {
|
||||
|
||||
app.add_plugins(backpack::plugin);
|
||||
app.add_plugins(client::plugin);
|
||||
app.add_plugins(control::plugin);
|
||||
app.add_plugins(debug::plugin);
|
||||
app.add_plugins(enemy::plugin);
|
||||
app.add_plugins(heal_effect::plugin);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::GameState;
|
||||
use crate::{GameState, control::CharacterInputEnabled};
|
||||
use bevy::{color::palettes::css::BLACK, prelude::*};
|
||||
use shared::{HEDZ_GREEN, HEDZ_PURPLE, control::CharacterInputEnabled, loading_assets::UIAssets};
|
||||
use shared::{HEDZ_GREEN, HEDZ_PURPLE, loading_assets::UIAssets};
|
||||
|
||||
#[derive(States, Default, Clone, Eq, PartialEq, Debug, Hash)]
|
||||
#[states(scoped_entities)]
|
||||
|
||||
Reference in New Issue
Block a user