pub struct ActionState<A: Actionlike> {
    pub action_data: Vec<ActionData>,
    /* 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 leafwing_input_manager::prelude::*;
use bevy::utils::Instant;

#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Debug)]
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));

Fields

action_data: Vec<ActionData>

The ActionData of each action

The position in this vector corresponds to Actionlike::index.

Implementations

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.

Advances the time for all actions

The underlying Timing and ButtonState will be advanced according to the current_instant.

  • if no [Instant] is set, the current_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 leafwing_input_manager::prelude::*;
use leafwing_input_manager::buttonlike::ButtonState;
use bevy::utils::Instant;

#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug)]
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));

Gets a copy 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 leafwing_input_manager::prelude::*;

#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug)]
enum Action {
    Run,
    Jump,
}
let mut action_state = ActionState::<Action>::default();
let run_data = action_state.action_data(Action::Run);

dbg!(run_data);

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 of 1.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 the axis_inputs example in the repository.
  • Dual axis inputs will return the magnitude of its [AxisPair] and will be in the range 0.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.

Get the value associated with the corresponding action, clamped to [-1.0, 1.0].

Get the DualAxisData from the binding that triggered the corresponding action.

Only certain events such as [VirtualDPad][crate::user_input::VirtualDPad] and [DualAxis][crate::user_input::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.

Get the DualAxisData associated with the corresponding action, clamped to [-1.0, 1.0].

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 leafwing_input_manager::prelude::*;

#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug)]
enum AbilitySlot {
    Slot1,
    Slot2,
}

#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug)]
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);

Press the action

No initial instant or reasons why the button was pressed will be recorded Instead, this is set through ActionState::tick()

Release the action

No initial instant will be recorded Instead, this is set through ActionState::tick()

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 leafwing_input_manager::prelude::*;

#[derive(Actionlike, Clone, Copy, PartialEq, Eq, Debug)]
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));

Releases all actions

Is this action currently pressed?

Was this action pressed since the last time tick was called?

Is this action currently released?

This is always the logical negation of pressed

Was this action released since the last time tick was called?

Which actions are currently pressed?

Which actions were just pressed?

Which actions are currently released?

Which actions were just released?

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.

The Duration for which the action has been held or released

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

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Deserialize this value from the given Serde deserializer. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Return the T [ShaderType] for self. When used in [AsBindGroup] derives, it is safe to assume that all images in self exist. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Convert 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. Read more

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait. Read more

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s. Read more

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s. Read more

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait. Read more

Returns the argument unchanged.

Creates Self using data from the given [World]

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more