Struct leafwing_input_manager::action_state::ActionState
source · pub struct ActionState<A: Actionlike> { /* private fields */ }
Expand description
Stores the canonical input-method-agnostic representation of the inputs received
Can be used as either a resource or as a [Component
] on entities that you wish to control directly from player input.
Example
use bevy::reflect::Reflect;
use leafwing_input_manager::prelude::*;
use bevy::utils::Instant;
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Debug, Reflect)]
enum Action {
Left,
Right,
Jump,
}
let mut action_state = ActionState::<Action>::default();
// Typically, this is done automatically by the `InputManagerPlugin` from user inputs
// using the `ActionState::update` method
action_state.press(Action::Jump);
assert!(action_state.pressed(Action::Jump));
assert!(action_state.just_pressed(Action::Jump));
assert!(action_state.released(Action::Left));
// Resets just_pressed and just_released
let t0 = Instant::now();
let t1 = Instant::now();
action_state.tick(t1, t0);
assert!(action_state.pressed(Action::Jump));
assert!(!action_state.just_pressed(Action::Jump));
action_state.release(Action::Jump);
assert!(!action_state.pressed(Action::Jump));
assert!(action_state.released(Action::Jump));
assert!(action_state.just_released(Action::Jump));
let t2 = Instant::now();
action_state.tick(t2, t1);
assert!(action_state.released(Action::Jump));
assert!(!action_state.just_released(Action::Jump));
Implementations§
source§impl<A: Actionlike> ActionState<A>
impl<A: Actionlike> ActionState<A>
sourcepub fn update(&mut self, action_data: Vec<ActionData>)
pub fn update(&mut self, action_data: Vec<ActionData>)
Updates the ActionState
based on a vector of ActionData
, ordered by Actionlike::id
.
The action_data
is typically constructed from InputMap::which_pressed
,
which reads from the assorted Input
resources.
sourcepub fn tick(&mut self, current_instant: Instant, previous_instant: Instant)
pub fn tick(&mut self, current_instant: Instant, previous_instant: Instant)
Advances the time for all actions
The underlying Timing
and ButtonState
will be advanced according to the current_instant
.
- if no [
Instant
] is set, thecurrent_instant
will be set as the initial time at which the button was pressed / released - the
Duration
will advance to reflect elapsed time
Example
use bevy::prelude::Reflect;
use leafwing_input_manager::prelude::*;
use leafwing_input_manager::buttonlike::ButtonState;
use bevy::utils::Instant;
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum Action {
Run,
Jump,
}
let mut action_state = ActionState::<Action>::default();
// Actions start released
assert!(action_state.released(Action::Jump));
assert!(!action_state.just_released(Action::Run));
// Ticking time moves causes buttons that were just released to no longer be just released
let t0 = Instant::now();
let t1 = Instant::now();
action_state.tick(t1, t0);
assert!(action_state.released(Action::Jump));
assert!(!action_state.just_released(Action::Jump));
action_state.press(Action::Jump);
assert!(action_state.just_pressed(Action::Jump));
// Ticking time moves causes buttons that were just pressed to no longer be just pressed
let t2 = Instant::now();
action_state.tick(t2, t1);
assert!(action_state.pressed(Action::Jump));
assert!(!action_state.just_pressed(Action::Jump));
sourcepub fn action_data(&self, action: A) -> &ActionData
pub fn action_data(&self, action: A) -> &ActionData
A reference to the ActionData
of the corresponding action
Generally, it’ll be clearer to call pressed
or so on directly on the ActionState
.
However, accessing the raw data directly allows you to examine detailed metadata holistically.
Example
use bevy::prelude::Reflect;
use leafwing_input_manager::prelude::*;
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum Action {
Run,
Jump,
}
let mut action_state = ActionState::<Action>::default();
let run_data = action_state.action_data(Action::Run);
dbg!(run_data);
sourcepub fn action_data_mut(&mut self, action: A) -> &mut ActionData
pub fn action_data_mut(&mut self, action: A) -> &mut ActionData
A mutable reference of the ActionData
of the corresponding action
Generally, it’ll be clearer to call pressed
or so on directly on the ActionState
.
However, accessing the raw data directly allows you to examine detailed metadata holistically.
Example
use bevy::prelude::Reflect;
use leafwing_input_manager::prelude::*;
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum Action {
Run,
Jump,
}
let mut action_state = ActionState::<Action>::default();
let mut run_data = action_state.action_data_mut(Action::Run);
run_data.axis_pair = None;
dbg!(run_data);
sourcepub fn value(&self, action: A) -> f32
pub fn value(&self, action: A) -> f32
Get the value associated with the corresponding action
Different kinds of bindings have different ways of calculating the value:
- Binary buttons will have a value of
0.0
when the button is not pressed, and a value of1.0
when the button is pressed. - Some axes, such as an analog stick, will have a value in the range
-1.0..=1.0
. - Some axes, such as a variable trigger, will have a value in the range
0.0..=1.0
. - Some buttons will also return a value in the range
0.0..=1.0
, such as analog gamepad triggers which may be tracked as buttons or axes. Examples of these include the Xbox LT/RT triggers and the Playstation L2/R2 triggers. See also theaxis_inputs
example in the repository. - Dual axis inputs will return the magnitude of its
DualAxisData
and will be in the range0.0..=1.0
. - Chord inputs will return the value of its first input.
If multiple inputs trigger the same game action at the same time, the value of each triggering input will be added together.
Warning
This value may not be bounded as you might expect.
Consider clamping this to account for multiple triggering inputs,
typically using the clamped_value
method instead.
sourcepub fn clamped_value(&self, action: A) -> f32
pub fn clamped_value(&self, action: A) -> f32
Get the value associated with the corresponding action
, clamped to [-1.0, 1.0]
.
sourcepub fn axis_pair(&self, action: A) -> Option<DualAxisData>
pub fn axis_pair(&self, action: A) -> Option<DualAxisData>
Get the DualAxisData
from the binding that triggered the corresponding action
.
Only certain events such as VirtualDPad
and
DualAxis
provide an DualAxisData
, and this
will return None
for other events.
Chord inputs will return the DualAxisData
of it’s first input.
If multiple inputs with an axis pair trigger the same game action at the same time, the value of each axis pair will be added together.
Warning
These values may not be bounded as you might expect.
Consider clamping this to account for multiple triggering inputs,
typically using the clamped_axis_pair
method instead.
sourcepub fn clamped_axis_pair(&self, action: A) -> Option<DualAxisData>
pub fn clamped_axis_pair(&self, action: A) -> Option<DualAxisData>
Get the DualAxisData
associated with the corresponding action
, clamped to [-1.0, 1.0]
.
sourcepub fn set_action_data(&mut self, action: A, data: ActionData)
pub fn set_action_data(&mut self, action: A, data: ActionData)
Manually sets the ActionData
of the corresponding action
You should almost always use more direct methods, as they are simpler and less error-prone.
However, this method can be useful for testing,
or when transferring ActionData
between action states.
Example
use bevy::prelude::Reflect;
use leafwing_input_manager::prelude::*;
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum AbilitySlot {
Slot1,
Slot2,
}
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum Action {
Run,
Jump,
}
let mut ability_slot_state = ActionState::<AbilitySlot>::default();
let mut action_state = ActionState::<Action>::default();
// Extract the state from the ability slot
let slot_1_state = ability_slot_state.action_data(AbilitySlot::Slot1);
// And transfer it to the actual ability that we care about
// without losing timing information
action_state.set_action_data(Action::Run, slot_1_state.clone());
sourcepub fn press(&mut self, action: A)
pub fn press(&mut self, action: A)
Press the action
No initial instant or reasons why the button was pressed will be recorded
Instead, this is set through ActionState::tick()
sourcepub fn release(&mut self, action: A)
pub fn release(&mut self, action: A)
Release the action
No initial instant will be recorded
Instead, this is set through ActionState::tick()
sourcepub fn consume(&mut self, action: A)
pub fn consume(&mut self, action: A)
Consumes the action
The action will be released, and will not be able to be pressed again
until it would have otherwise been released by ActionState::release
,
ActionState::release_all
or ActionState::update
.
No initial instant will be recorded
Instead, this is set through ActionState::tick()
Example
use bevy::prelude::Reflect;
use leafwing_input_manager::prelude::*;
#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug, Reflect)]
enum Action {
Eat,
Sleep,
}
let mut action_state = ActionState::<Action>::default();
action_state.press(Action::Eat);
assert!(action_state.pressed(Action::Eat));
// Consuming actions releases them
action_state.consume(Action::Eat);
assert!(action_state.released(Action::Eat));
// Doesn't work, as the action was consumed
action_state.press(Action::Eat);
assert!(action_state.released(Action::Eat));
// Releasing consumed actions allows them to be pressed again
action_state.release(Action::Eat);
action_state.press(Action::Eat);
assert!(action_state.pressed(Action::Eat));
sourcepub fn consume_all(&mut self)
pub fn consume_all(&mut self)
Consumes all actions
sourcepub fn release_all(&mut self)
pub fn release_all(&mut self)
Releases all actions
sourcepub fn just_pressed(&self, action: A) -> bool
pub fn just_pressed(&self, action: A) -> bool
Was this action
pressed since the last time tick was called?
sourcepub fn released(&self, action: A) -> bool
pub fn released(&self, action: A) -> bool
Is this action
currently released?
This is always the logical negation of pressed
sourcepub fn just_released(&self, action: A) -> bool
pub fn just_released(&self, action: A) -> bool
Was this action
released since the last time tick was called?
sourcepub fn get_pressed(&self) -> Vec<A>
pub fn get_pressed(&self) -> Vec<A>
Which actions are currently pressed?
sourcepub fn get_just_pressed(&self) -> Vec<A>
pub fn get_just_pressed(&self) -> Vec<A>
Which actions were just pressed?
sourcepub fn get_released(&self) -> Vec<A>
pub fn get_released(&self) -> Vec<A>
Which actions are currently released?
sourcepub fn get_just_released(&self) -> Vec<A>
pub fn get_just_released(&self) -> Vec<A>
Which actions were just released?
sourcepub fn instant_started(&self, action: A) -> Option<Instant>
pub fn instant_started(&self, action: A) -> Option<Instant>
The [Instant
] that the action was last pressed or released
If the action was pressed or released since the last time ActionState::tick
was called
the value will be None
.
This ensures that all of our actions are assigned a timing and duration
that corresponds exactly to the start of a frame, rather than relying on idiosyncratic timing.
sourcepub fn current_duration(&self, action: A) -> Duration
pub fn current_duration(&self, action: A) -> Duration
The Duration
for which the action has been held or released
sourcepub fn previous_duration(&self, action: A) -> Duration
pub fn previous_duration(&self, action: A) -> Duration
The Duration
for which the action was last held or released
This is a snapshot of the ActionState::current_duration
state at the time
the action was last pressed or released.
Trait Implementations§
source§impl<A: Clone + Actionlike> Clone for ActionState<A>
impl<A: Clone + Actionlike> Clone for ActionState<A>
source§fn clone(&self) -> ActionState<A>
fn clone(&self) -> ActionState<A>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moresource§impl<A: Actionlike> Component for ActionState<A>
impl<A: Actionlike> Component for ActionState<A>
source§impl<A: Debug + Actionlike> Debug for ActionState<A>
impl<A: Debug + Actionlike> Debug for ActionState<A>
source§impl<A: Actionlike> Default for ActionState<A>
impl<A: Actionlike> Default for ActionState<A>
source§fn default() -> ActionState<A>
fn default() -> ActionState<A>
source§impl<'de, A: Actionlike> Deserialize<'de> for ActionState<A>
impl<'de, A: Actionlike> Deserialize<'de> for ActionState<A>
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
source§impl<A> FromReflect for ActionState<A>where
Vec<ActionData>: FromReflect,
PhantomData<A>: Any + Send + Sync + Default,
A: TypePath + Actionlike,
impl<A> FromReflect for ActionState<A>where
Vec<ActionData>: FromReflect,
PhantomData<A>: Any + Send + Sync + Default,
A: TypePath + Actionlike,
source§fn from_reflect(reflect: &dyn Reflect) -> Option<Self>
fn from_reflect(reflect: &dyn Reflect) -> Option<Self>
Self
from a reflected value.§fn take_from_reflect(
reflect: Box<dyn Reflect>
) -> Result<Self, Box<dyn Reflect>>
fn take_from_reflect( reflect: Box<dyn Reflect> ) -> Result<Self, Box<dyn Reflect>>
Self
using,
constructing the value using from_reflect
if that fails. Read moresource§impl<A> GetTypeRegistration for ActionState<A>
impl<A> GetTypeRegistration for ActionState<A>
fn get_type_registration() -> TypeRegistration
source§impl<A: PartialEq + Actionlike> PartialEq for ActionState<A>
impl<A: PartialEq + Actionlike> PartialEq for ActionState<A>
source§fn eq(&self, other: &ActionState<A>) -> bool
fn eq(&self, other: &ActionState<A>) -> bool
self
and other
values to be equal, and is used
by ==
.source§impl<A> Reflect for ActionState<A>
impl<A> Reflect for ActionState<A>
source§fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
fn get_represented_type_info(&self) -> Option<&'static TypeInfo>
TypeInfo
] of the type represented by this value. Read moresource§fn as_any_mut(&mut self) -> &mut dyn Any
fn as_any_mut(&mut self) -> &mut dyn Any
&mut dyn Any
.source§fn into_reflect(self: Box<Self>) -> Box<dyn Reflect>
fn into_reflect(self: Box<Self>) -> Box<dyn Reflect>
source§fn as_reflect(&self) -> &dyn Reflect
fn as_reflect(&self) -> &dyn Reflect
source§fn as_reflect_mut(&mut self) -> &mut dyn Reflect
fn as_reflect_mut(&mut self) -> &mut dyn Reflect
source§fn clone_value(&self) -> Box<dyn Reflect>
fn clone_value(&self) -> Box<dyn Reflect>
Reflect
trait object. Read moresource§fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>
fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>
source§fn reflect_ref(&self) -> ReflectRef<'_>
fn reflect_ref(&self) -> ReflectRef<'_>
source§fn reflect_mut(&mut self) -> ReflectMut<'_>
fn reflect_mut(&mut self) -> ReflectMut<'_>
source§fn reflect_owned(self: Box<Self>) -> ReflectOwned
fn reflect_owned(self: Box<Self>) -> ReflectOwned
source§fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool>
fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option<bool>
§fn type_name(&self) -> &str
fn type_name(&self) -> &str
§fn reflect_hash(&self) -> Option<u64>
fn reflect_hash(&self) -> Option<u64>
§fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>
§fn serializable(&self) -> Option<Serializable<'_>>
fn serializable(&self) -> Option<Serializable<'_>>
§fn is_dynamic(&self) -> bool
fn is_dynamic(&self) -> bool
source§impl<A: Actionlike> Serialize for ActionState<A>
impl<A: Actionlike> Serialize for ActionState<A>
source§impl<A> Struct for ActionState<A>
impl<A> Struct for ActionState<A>
source§fn field(&self, name: &str) -> Option<&dyn Reflect>
fn field(&self, name: &str) -> Option<&dyn Reflect>
name
as a &dyn Reflect
.source§fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>
fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>
name
as a
&mut dyn Reflect
.source§fn field_at(&self, index: usize) -> Option<&dyn Reflect>
fn field_at(&self, index: usize) -> Option<&dyn Reflect>
index
as a
&dyn Reflect
.source§fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>
fn field_at_mut(&mut self, index: usize) -> Option<&mut dyn Reflect>
index
as a &mut dyn Reflect
.source§fn name_at(&self, index: usize) -> Option<&str>
fn name_at(&self, index: usize) -> Option<&str>
index
.source§fn iter_fields(&self) -> FieldIter<'_>
fn iter_fields(&self) -> FieldIter<'_>
source§fn clone_dynamic(&self) -> DynamicStruct
fn clone_dynamic(&self) -> DynamicStruct
DynamicStruct
].source§impl<A> TypePath for ActionState<A>
impl<A> TypePath for ActionState<A>
source§fn type_path() -> &'static str
fn type_path() -> &'static str
source§fn short_type_path() -> &'static str
fn short_type_path() -> &'static str
source§fn type_ident() -> Option<&'static str>
fn type_ident() -> Option<&'static str>
source§fn crate_name() -> Option<&'static str>
fn crate_name() -> Option<&'static str>
source§impl<A> Typed for ActionState<A>
impl<A> Typed for ActionState<A>
impl<A: Actionlike> Resource for ActionState<A>
impl<A: Actionlike> StructuralPartialEq for ActionState<A>
Auto Trait Implementations§
impl<A> RefUnwindSafe for ActionState<A>where
A: RefUnwindSafe,
impl<A> Send for ActionState<A>
impl<A> Sync for ActionState<A>
impl<A> Unpin for ActionState<A>where
A: Unpin,
impl<A> UnwindSafe for ActionState<A>where
A: UnwindSafe,
Blanket Implementations§
§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
[ShaderType
] for self
. When used in [AsBindGroup
]
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<C> Bundle for Cwhere
C: Component,
impl<C> Bundle for Cwhere
C: Component,
fn component_ids( components: &mut Components, storages: &mut Storages, ids: &mut impl FnMut(ComponentId) )
unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.§impl<T> DowncastSync for T
impl<T> DowncastSync for T
§impl<C> DynamicBundle for Cwhere
C: Component,
impl<C> DynamicBundle for Cwhere
C: Component,
fn get_components(self, func: &mut impl FnMut(StorageType, OwningPtr<'_>))
§impl<T> DynamicTypePath for Twhere
T: TypePath,
impl<T> DynamicTypePath for Twhere
T: TypePath,
§fn reflect_type_path(&self) -> &str
fn reflect_type_path(&self) -> &str
TypePath::type_path
].§fn reflect_short_type_path(&self) -> &str
fn reflect_short_type_path(&self) -> &str
TypePath::short_type_path
].§fn reflect_type_ident(&self) -> Option<&str>
fn reflect_type_ident(&self) -> Option<&str>
TypePath::type_ident
].§fn reflect_crate_name(&self) -> Option<&str>
fn reflect_crate_name(&self) -> Option<&str>
TypePath::crate_name
].§fn reflect_module_path(&self) -> Option<&str>
fn reflect_module_path(&self) -> Option<&str>
TypePath::module_path
].§impl<T> FromWorld for Twhere
T: Default,
impl<T> FromWorld for Twhere
T: Default,
§fn from_world(_world: &mut World) -> T
fn from_world(_world: &mut World) -> T
Self
using data from the given [World
].§impl<S> GetField for Swhere
S: Struct,
impl<S> GetField for Swhere
S: Struct,
§impl<T> GetPath for Twhere
T: Reflect + ?Sized,
impl<T> GetPath for Twhere
T: Reflect + ?Sized,
§fn reflect_path<'p>(
&self,
path: impl ReflectPath<'p>
) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>
fn reflect_path<'p>( &self, path: impl ReflectPath<'p> ) -> Result<&(dyn Reflect + 'static), ReflectPathError<'p>>
path
. Read more§fn reflect_path_mut<'p>(
&mut self,
path: impl ReflectPath<'p>
) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>
fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p> ) -> Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>
path
. Read more