TweenAnim

Struct TweenAnim 

Source
pub struct TweenAnim {
    pub playback_state: PlaybackState,
    pub speed: f64,
    pub destroy_on_completion: bool,
    /* private fields */
}
Expand description

Animation controller instance.

The TweenAnim represents a single animation instance for a single target (component or resource or asset). Each instance is independent, even if it mutates the same target as another instance. Spawning this component adds an active animation, and destroying it stops that animation. The component can also be used to control the animation playback at runtime, like the playback speed.

The target is described by the AnimTarget component. If that component is absent, then the animation implicitly targets a component on the current Entity. The type of the component is derived from the type that the Lens animates.

If you’re looking for the basic tweenable animation description, see Tween instead.

§Example

fn my_system(mut commands: Commands) {
    let tweenable = make_tweenable::<Transform>();
    let id1 = commands
        .spawn((
            Transform::default(),
            // Implicitly targets the current entity's Transform
            TweenAnim::new(tweenable),
        ))
        .id();

    let tweenable2 = make_tweenable::<Transform>();
    commands.spawn((
        TweenAnim::new(tweenable2),
        // Explicitly targets the Transform component of entity 'id1'
        AnimTarget::component::<Transform>(id1),
    ));
}

Fields§

§playback_state: PlaybackState

Control if the animation is played or not. Defaults to PlaybackState::Playing.

Pausing an animation with PlaybackState::Paused is functionaly equivalent to setting its speed to zero. The two fields remain independent though, for convenience.

§speed: f64

Relative playback speed. Defaults to 1. (normal speed; 100%).

Setting a negative or zero speed value effectively pauses the animation (although the playback_state remains unchanged). Negative values may be clamped to 0. when the animation is stepped, but positive or zero values are never modified by the library.

§Time precision

This note is an implementation detail which can usually be ignored.

Despite the use of f64, setting a playback speed different from 1. (100% speed) may produce small inaccuracies in durations, especially for longer animations. However those are often negligible. This is due to the very large precision of Duration (typically 96 bits or more), even compared to f64 (64 bits), and the fact this speed factor is a multiplier whereas most other time quantities are added or subtracted.

§destroy_on_completion: bool

Destroy the animation once completed. This defaults to true, and makes the stepping functions like TweenAnim::step_all() destroy this animation once it completed. To keep the animation queued, and allow access after it completed, set this to false. Note however that you should avoid leaving all animations queued if they’re unused, as this wastes memory and may degrade performances if too many completed animations are kept around for no good reason.

Implementations§

Source§

impl TweenAnim

Source

pub fn new(tweenable: impl IntoBoxedTweenable) -> Self

Create a new tween animation.

This component represents the runtime animation being played to mutate a specific target.

§Panics

Panics if the tweenable is “typeless”, that is Tweenable::target_type_id() returns None. Animations must target a concrete component or asset type. This means in particular that you can’t use a single Delay alone. You can however use a Delay or other typeless tweenables as part of a Sequence, provided there’s at least one other typed tweenable in the sequence to make it typed too.

Source

pub fn with_speed(self, speed: f64) -> Self

Configure the playback speed.

Source

pub fn with_destroy_on_completed(self, destroy_on_completed: bool) -> Self

Enable or disable destroying this component on animation completion.

If enabled, the component is automatically removed from its Entity when the animation completed.

Source

pub fn step_one( world: &mut World, delta_time: Duration, entity: Entity, ) -> Result<(), TweeningError>

Step a single animation.

The step_all() function is called automatically by the animation system registered by the TweeningPlugin, you generally don’t need to call this one.

This is a shortcut for step_many(world, delta_time, [entity]), with the added benefit that it returns some error if the entity is not valid. See step_many() for details.

§Example
#[derive(Component)]
struct MyMarker;

fn my_system(world: &mut World) -> Result<()> {
    let mut q_anims = world.query_filtered::<Entity, (With<TweenAnim>, With<MyMarker>)>();
    let entity = q_anims.single(world)?;
    let delta_time = Duration::from_millis(200);
    TweenAnim::step_one(world, delta_time, entity);
    Ok(())
}
§Returns

This returns an error if the entity is not found or doesn’t own a TweenAnim component.

Source

pub fn step_many( world: &mut World, delta_time: Duration, anims: &[Entity], ) -> usize

Step some animation(s).

The step_all() function is called automatically by the animation system registered by the TweeningPlugin, you generally don’t need to call this one.

Step the given animation(s) by a given delta_time, which may be Duration::ZERO. Passing a zero delta time may be useful to force the current animation state to be applied to a target, in case you made change which do not automatically do so (for example, retargeting an animation). The anims are the entities which own a TweenAnim component to step; any entity without a TweenAnim component is silently ignored.

The function doesn’t check that all input entities are unique. If an entity is duplicated in anims, the behavior is undefined, including (but not guaranteed) stepping the animation multiple times. You’re responsible for ensuring the input entity slice contains distinct entities.

§Example
#[derive(Component)]
struct MyMarker;

fn my_system(world: &mut World) -> Result<()> {
    let mut q_anims = world.query_filtered::<Entity, (With<TweenAnim>, With<MyMarker>)>();
    let entities = q_anims.iter(world).collect::<Vec<Entity>>();
    let delta_time = Duration::from_millis(200);
    TweenAnim::step_many(world, delta_time, &entities[..]);
    Ok(())
}
§Returns

Returns the number of TweenAnim component found and stepped, which is always less than or equal to the input anims slice length.

Source

pub fn step_all(world: &mut World, delta_time: Duration)

Step all animations on the given world.

This function is called automatically by the animation system registered by the TweeningPlugin, you generally don’t need to call it.

Step all the TweenAnim components of the input world by a given delta_time, which may be Duration::ZERO. Passing a zero delta time may be useful to force the current animation state to be applied to a target, in case you made change which do not automatically do so (for example, retargeting an animation).

Source

pub fn stop(&mut self)

Stop animation playback and rewind the animation.

This changes the animator state to PlaybackState::Paused and rewinds its tweenable.

§Panics

Like Tweenable::rewind(), this panics if the current playback direction is PlaybackDirection::Backward and the animation is infinitely repeating.

Source

pub fn tweenable(&self) -> &dyn Tweenable

Get the tweenable describing this animation.

To change the tweenable, use TweenAnim::set_tweenable().

Source

pub fn set_tweenable<T>( &mut self, tweenable: T, ) -> Result<BoxedTweenable, TweeningError>
where T: Tweenable + 'static,

Set a new animation description.

Attempt to change the tweenable of an animation already spawned.

If the tweenable is successfully swapped, this resets the tween_state() to TweenState::Active, even if the tweenable would otherwise be completed e.g. because its current elapsed time is past its total duration. Conversely, this doesn’t update the target component or asset, as this function doesn’t have mutable access to it. To force applying the new state to the target without stepping the animation forward or backward, call one of the stepping functions like TweenAnim::step_one() passing a delta time of Duration::ZERO.

To ensure the old and new animations have the same elapsed time (for example if they need to be synchronized, if they’re variants of each other), call set_elapsed() first on the input tweenable, with the duration value of the old tweenable returned by elapsed().

fn my_system(mut anim: Single<&mut TweenAnim>) {
    let mut tweenable = make_tweenable();
    let elapsed = anim.tweenable().elapsed();
    tweenable.set_elapsed(elapsed);
    anim.set_tweenable(tweenable);
}
§Returns

On success, returns the previous tweenable which has been swapped out.

Source

pub fn tween_state(&self) -> TweenState

Get the tweening completion state.

In general this is TweenState::Active, unless the animation completed and destroy_on_completion is false.

Trait Implementations§

Source§

impl Component for TweenAnim
where Self: Send + Sync + 'static,

Source§

const STORAGE_TYPE: StorageType = ::bevy::ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_replace ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ids: &mut impl FnMut(ComponentId), )

Source§

fn get_component_ids( components: &Components, ids: &mut impl FnMut(Option<ComponentId>), )

Gets this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

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

fn in_current_span(self) -> Instrumented<Self>

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

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,