Tween

Struct Tween 

Source
pub struct Tween { /* private fields */ }
Expand description

Single tweening animation description.

A tween is the basic building block of an animation. It describes a single tweening animation between two values, accessed through a given Lens. The animation is composed of one or more cycles, and can be played forward or backward. On completion, you can be notified via events, observers, or the execution of a one-shot system.

If you’re looking for the runtime representation of a tweenable animation, see TweenAnim instead.

§Cycles

A tween can be configured to repeat multiple, or even an infinity, of times. Each repeat iteration is called a cycle. The duration of a single cycle is the cycle duration, and the duration of the entire tween animation including all cycles is the total duration.

<sodipodi:namedview id=“namedview1” pagecolor=“#ffffff” bordercolor=“#000000” borderopacity=“0.25” inkscape:showpageshadow=“2” inkscape:pageopacity=“0.0” inkscape:pagecheckerboard=“0” inkscape:deskcolor=“#d1d1d1” inkscape:document-units=“mm” showgrid=“true” inkscape:zoom=“2.1774144” inkscape:cx=“144.20773” inkscape:cy=“139.3855” inkscape:window-width=“1728” inkscape:window-height=“962” inkscape:window-x=“0” inkscape:window-y=“38” inkscape:window-maximized=“1” inkscape:current-layer=“layer1”> <inkscape:grid id=“grid1” units=“mm” originx=“-3.7795274” originy=“-37.795285” spacingx=“3.7795276” spacingy=“3.7795276” empcolor=“#0099e5” empopacity=“0.30196078” color=“#0099e5” opacity=“0.14901961” empspacing=“5” dotted=“false” gridanglex=“30” gridanglez=“30” visible=“true” /> </sodipodi:namedview> ratio time total duration 0 1 cycle duration

An example tween with 5 cycles.

The number of cycles is configured through the RepeatCount.

  • RepeatCount::Finite directly sets a number of cycles. The total duration is inferred from the cycle duration and number of cycles.
  • RepeatCount::For selects a total duration for the animation, from which a number of cycles is derived. In that case, the number of cycles may be a fractional number; the last cycle is only partial, and may not reach the endpoint of the lens.
  • RepeatCount::Infinite enables infinitely-repeating cycles. In that case the total duration of the animation is infinite, and the animation itself is said to be infinite.

The repeat strategy determines whether cycles are mirrored when they repeat. By default, all cycles produce a linear ratio monotonically increasing from 0 to 1. When mirrored, every other cycle instead produces a decreasing ratio from 1 to 0. The repeat strategy is configured with RepeatStrategy.

<sodipodi:namedview id=“namedview1” pagecolor=“#ffffff” bordercolor=“#000000” borderopacity=“0.25” inkscape:showpageshadow=“2” inkscape:pageopacity=“0.0” inkscape:pagecheckerboard=“0” inkscape:deskcolor=“#d1d1d1” inkscape:document-units=“mm” showgrid=“true” inkscape:zoom=“2.1774144” inkscape:cx=“144.20773” inkscape:cy=“139.3855” inkscape:window-width=“1728” inkscape:window-height=“962” inkscape:window-x=“0” inkscape:window-y=“38” inkscape:window-maximized=“1” inkscape:current-layer=“layer1”> <inkscape:grid id=“grid1” units=“mm” originx=“-3.7795274” originy=“-37.795285” spacingx=“3.7795276” spacingy=“3.7795276” empcolor=“#0099e5” empopacity=“0.30196078” color=“#0099e5” opacity=“0.14901961” empspacing=“5” dotted=“false” gridanglex=“30” gridanglez=“30” visible=“true” /> </sodipodi:namedview> ratio time total duration 0 1 cycle duration

A tween with 5 cycles, using the mirrored repeat strategy.

Once the ratio in [0:1] has been calculated, it’s passed through the easing function to obtain the final interpolation factor that Lens::lerp() receives.

§Elapsed time and playback direction

The elapsed time of an animation represents the current time since the start of the animation. This includes all cycles, and is bound by the total duration of the animation. This is a property of an active animation, and is available per instance from the TweenAnim representing the instance. So a tween itself, which describes an animation without a specific target to animate, doesn’t have an elapsed time. You can think of the elapsed time as the current time position on some animation timeline.

The tween however has a playback direction. By default, the playback direction is PlaybackDirection::Forward, and the animation plays forward as described above. By instead using PlaybackDirection::Backward, the tween plays in reverse from end to start. Practically, this means that the elapsed time decreases from its current value back to zero, and the animation completes at t=0. You can think of the playback direction as the direction in which the time position moves on some animation timeline. Note that as a result, because infinite animations (RepeatCount::Infinite) don’t have an end time, they cannot be rewinded when the playback direction is backward.

§Completion events and one-shot systems

Sometimes, you want to be notified of the completion of an animation cycle, or the completion of the entire animation itself. To that end, the Tween supports several mechanisms:

Implementations§

Source§

impl Tween

Source

pub fn new<T, L>( ease_method: impl Into<EaseMethod>, cycle_duration: Duration, lens: L, ) -> Self
where T: 'static, L: Lens<T> + Send + Sync + 'static,

Create a new tween animation.

The new animation is described by a given cycle duration, a repeat count which determines its total duration, as well as an easing function and a lens describing how the cycles affect the animation target. The target type is implicitly determined by the type T of the Lens<T> argument.

§Example
let tween = Tween::new(
    EaseFunction::QuadraticInOut,
    Duration::from_secs(1),
    TransformPositionLens {
        start: Vec3::ZERO,
        end: Vec3::new(3.5, 0., 0.),
    },
);
Source

pub fn with_repeat_count(self, count: impl Into<RepeatCount>) -> Self

Set the number of times to repeat the animation.

The repeat count determines the number of cycles of the animation. See the top-level Tween documentation for details.

Source

pub fn set_repeat_count(&mut self, count: impl Into<RepeatCount>)

Set the number of times to repeat the animation.

The repeat count determines the number of cycles of the animation. See the top-level Tween documentation for details.

Source

pub fn with_repeat_strategy(self, strategy: RepeatStrategy) -> Self

Configure how the cycles repeat.

This enables or disables cycle mirroring. See the top-level Tween documentation for details.

Source

pub fn set_repeat_strategy(&mut self, strategy: RepeatStrategy)

Configure how the cycles repeat.

This enables or disables cycle mirroring. See the top-level Tween documentation for details.

Source

pub fn with_repeat( self, count: impl Into<RepeatCount>, strategy: RepeatStrategy, ) -> Self

Configure the animation repeat parameters.

The repeat count determines the number of cycles of the animation. The repeat strategy enables or disables cycle mirrored repeat. See the top-level Tween documentation for details.

Source

pub fn set_repeat( &mut self, count: impl Into<RepeatCount>, strategy: RepeatStrategy, )

Configure the animation repeat parameters.

The repeat count determines the number of cycles of the animation. The repeat strategy enables or disables cycle mirrored repeat. See the top-level Tween documentation for details.

Source

pub fn with_cycle_completed_event(self, send: bool) -> Self

Enable raising a event on cycle completion.

If enabled, the tween will raise a CycleCompletedEvent each time the tween completes a cycle (reaches or passes its cycle duration). In case of repeating tweens (repeat count > 1), the event is raised once per cycle. For mirrored repeats, a cycle is one travel from start to end or end to start, so the full loop start -> end -> start counts as 2 cycles and raises 2 events.

§Example
let tween = Tween::new(
    // [...]
)
// Raise a CycleCompletedEvent each cycle
.with_cycle_completed_event(true);

fn my_system(mut reader: EventReader<CycleCompletedEvent>) {
    for ev in reader.read() {
        println!(
            "Tween animation {:?} raised CycleCompletedEvent for target {:?}!",
            ev.anim_entity, ev.target
        );
    }
}
Source

pub fn set_cycle_completed_event(&mut self, send: bool)

Set whether the tween emits CycleCompletedEvent.

See with_cycle_completed_event() for details.

Source

pub fn set_playback_direction(&mut self, direction: PlaybackDirection)

Set the playback direction of the tween.

The playback direction controls whether the internal animation clock, and therefore also the elapsed time, both move forward or backward.

Changing the direction doesn’t change any target state, nor the elapsed time of the tween. Only the direction of playback from this moment potentially changes.

Source

pub fn with_playback_direction(self, direction: PlaybackDirection) -> Self

Set the playback direction of the tween.

See set_playback_direction() for details.

Source

pub fn playback_direction(&self) -> PlaybackDirection

The current animation playback direction.

This is the value set by the user with with_playback_direction() and set_playback_direction(). This is never changed by the animation playback itself.

See PlaybackDirection for details.

Source

pub fn then(self, tween: impl Tweenable + 'static) -> Sequence

Chain another Tweenable after this tween, making a Sequence with the two.

§Example
let tween1 = Tween::new(
    EaseFunction::QuadraticInOut,
    Duration::from_secs(1),
    TransformPositionLens {
        start: Vec3::ZERO,
        end: Vec3::new(3.5, 0., 0.),
    },
);
let tween2 = Tween::new(
    EaseFunction::QuadraticInOut,
    Duration::from_secs(1),
    TransformRotationLens {
        start: Quat::IDENTITY,
        end: Quat::from_rotation_x(90.0_f32.to_radians()),
    },
);
let seq = tween1.then(tween2);
Source

pub fn cycle_index(&self) -> u32

Get the elapsed cycle index (numbered from 0), accounting for finite endpoint.

If the elapsed time is equal to the total (finite) duration of the tween, then the cycle index is capped at the total number of cycles minus 1 (the tween doesn’t loop when reaching the end of its last cycle). This means that for a tween with N cycles, the index is always in 0..N, and therefore always index < N.

Source

pub fn cycle_fraction(&self) -> f32

Get the elapsed cycle fraction, accounting for finite endpoint.

The elapsed cycle fraction is the fraction alonside one cycle where the tween currently is. This ignores any mirroring. If the elapsed time is equal to the total (finite) duration of the tween, then the cycle fraction is capped at 1.0 (the tween doesn’t loop when reaching the end of its last cycle).

The returned value is always in [0:1] for finite tweens, with the value 1.0 returned only when the last cycle is completed, and in [0:1) for infinite tweens as they never complete.

Source

pub fn is_cycle_mirrored(&self) -> bool

Check if the current cycle is a mirrored cycle.

When the repeat strategy is RepeatStrategy::MirroredRepeat, every odd cycle index (numbered from 0) is mirrored when applying the tween’s lens. For any other strategy or single-cycle tween, this is always false.

Trait Implementations§

Source§

impl From<Tween> for BoxedTweenable

Source§

fn from(t: Tween) -> Self

Converts to this type from the input type.
Source§

impl Tweenable for Tween

Source§

fn cycle_duration(&self) -> Duration

Get the duration of a single cycle of the animation. Read more
Source§

fn total_duration(&self) -> TotalDuration

Get the total duration of the entire animation, including repeating. Read more
Source§

fn set_elapsed(&mut self, elapsed: Duration)

Set the current animation playback elapsed time. Read more
Source§

fn elapsed(&self) -> Duration

Get the current elapsed duration. Read more
Source§

fn step( &mut self, _tween_id: Entity, delta: Duration, target: MutUntyped<'_>, target_type_id: &TypeId, notify_cycle_completed: &mut dyn FnMut(), ) -> (TweenState, bool)

Step the tweenable. Read more
Source§

fn rewind(&mut self)

Rewind the animation to its starting state. Read more
Source§

fn target_type_id(&self) -> Option<TypeId>

Get the TypeId this tweenable targets. Read more
Source§

fn cycles_completed(&self) -> u32

Get the number of cycles completed. Read more
Source§

fn cycle_fraction(&self) -> f32

Get the completion fraction in [0:1] of the current cycle.

Auto Trait Implementations§

§

impl Freeze for Tween

§

impl !RefUnwindSafe for Tween

§

impl Send for Tween

§

impl Sync for Tween

§

impl Unpin for Tween

§

impl !UnwindSafe for Tween

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<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<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> IntoBoxedTweenable for T
where T: Tweenable + 'static,

Source§

fn into_boxed(self) -> Box<dyn Tweenable>

Convert to a BoxedTweenable.
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,