In mobile games it is often the case that you can start input on screen and have virtual joystick to control the character in game. This is a implmentation of that.
In this example there are no external dependencies, just Bevy.
//! A Bevy plugin providing a UI node that behaves like a joystick area,
//! allowing relative cursor movement tracking for game or UI input purposes.
usebevy::{ecs::system::SystemParam,picking::pointer::PointerId,prelude::*};/// A Bevy plugin that registers the `JoystickNodeArea` component and sets up
/// the `update_joystick` system for handling joystick interactions.
pubstructJoystickNodePlugin;implPlugin forJoystickNodePlugin{fnbuild(&self, app:&mut App){ app.register_type::<JoystickNodeArea>().register_type::<JoystickNodeInputStart>().add_observer(add_joystick_observers);}}/// SystemParam helper for accessing `JoystickNodeArea`
#[derive(SystemParam, DerefMut, Deref)]pubstructSingleJoystick<'w>(pub Option<Single<'w, &'static JoystickNodeArea>>);implSingleJoystick<'_>{/// Calculates the current movement vector from the start position to the current cursor position.
////// The Y-axis is inverted to match screen coordinates.
pubfnget_movement(&self)->Option<Vec2>{ifletSome(Some(axis))=self.as_ref().map(|j|j.get_movement()){return axis.into();}None}/// Returns if Joystick area exists and is currently pressed
pubfnis_pressed(&self)->Option<bool>{self.as_ref().map(|j|j.is_pressed())}}/// A UI component representing a joystick interaction zone.
/// Tracks the cursor's start and current positions when pressed,
/// enabling directional movement calculation.
#[derive(Default, Debug, Reflect, Component)]#[require( bevy::ui::FocusPolicy = bevy::ui::FocusPolicy::Block, Interaction, Pickable, Node
)]#[reflect(Component)]pubstructJoystickNodeArea{/// The current direction of the cursor, in normalized coordinates.
current_dir:Option<Vec2>,
}/// Tracks the pointer start position and ID
#[derive(Default, Debug, Reflect, Component)]#[reflect(Component)]#[require(JoystickNodeArea)]pubstructJoystickNodeInputStart{/// The position where the cursor initially pressed down, in normalized coordinates.
pubpos: Vec2,
/// The ID of the pointer that is currently pressing the joystick.
pubid: PointerId,
}implFrom<&Pointer<Pressed>>forJoystickNodeInputStart{fnfrom(pointer:&Pointer<Pressed>)->Self{ JoystickNodeInputStart { pos: pointer.pointer_location.position, id: pointer.pointer_id,}}}implJoystickNodeArea{/// Calculates the current movement vector from the start position to the current cursor position.
////// The Y-axis is inverted to match screen coordinates.
pubfnupdate_dir(&mutself, start_data:&JoystickNodeInputStart, new_pos: Vec2){self.current_dir =Some((new_pos - start_data.pos)*Vec2::new(1.0,-1.0).normalize_or_zero());}/// Returns the current direction of the cursor
pubfnget_movement(&self)->Option<Vec2>{self.current_dir
}pubfnclear(&mutself){self.current_dir =None;}/// Returns if Joystick area is currently pressed
pubfnis_pressed(&self)->bool{self.current_dir.is_some()}}fnadd_joystick_observers(trigger:Trigger<OnAdd, JoystickNodeArea>, mutcommands: Commands){ commands
.entity(trigger.target()).with_child(Observer::new(on_remove_start_info).with_entity(trigger.target())).with_child(Observer::new(joystick_release).with_entity(trigger.target())).with_child(Observer::new(joystick_update).with_entity(trigger.target())).with_child(Observer::new(joystick_start).with_entity(trigger.target()));}fnon_remove_start_info(trigger:Trigger<OnRemove, JoystickNodeInputStart>,
mutq:Query<&mut JoystickNodeArea>,
){ifletOk(mut area)= q.get_mut(trigger.target()){ area.clear();}}fnjoystick_start(trigger:Trigger<Pointer<Pressed>>,
mutcommands: Commands,
q:Query<(), (With<JoystickNodeArea>, Without<JoystickNodeInputStart>)>,
){if q.get(trigger.target).is_err(){return;}let input_start: JoystickNodeInputStart = trigger.event().into(); commands.entity(trigger.target).try_insert(input_start);}fnjoystick_release(trigger:Trigger<Pointer<Released>>,
mutcommands: Commands,
mutq:Query<&JoystickNodeInputStart>,
){letOk(start_data)= q.get_mut(trigger.target)else{return;};if start_data.id == trigger.event().pointer_id { commands
.entity(trigger.target).try_remove::<JoystickNodeInputStart>();}}fnjoystick_update(trigger:Trigger<Pointer<Move>>,
mutq:Query<(&mut JoystickNodeArea, &JoystickNodeInputStart)>,
){letOk((mut joystick, start_data))= q.get_mut(trigger.target())else{return;};if start_data.id == trigger.pointer_id { joystick.update_dir(&*start_data, trigger.pointer_location.position);}}