Crate bevy_tweening

Crate bevy_tweening 

Source
Expand description

Tweening animation plugin for the Bevy game engine.

🍃 Bevy Tweening provides interpolation-based animation between (“tweening”) two values, to animate any field of any component, resource, or asset, including both built-in Bevy ones and custom user-defined ones. Each field of a component, resource, or asset, can be animated via a collection of predefined easing functions, or providing a custom animation curve. The library supports any number of animations queued in parallel, even on the same component, resource, or asset type, and allows runtime control over playback and animation speed.

§Quick start

Look at the documentation for:

  • Tween – the description of a tweening animation and the explanation of some core concepts
  • TweenAnim – the component representing the runtime animation
  • AnimTarget – the component defining the target that the animation mutates
  • TweeningPlugin – the plugin to add to your app
  • EntityCommandsTweeningExtensions – the simplest way to spawn animations

§Example

Add the TweeningPlugin to your app:

use bevy::prelude::*;
use bevy_tweening::*;

App::default()
    .add_plugins(DefaultPlugins)
    .add_plugins(TweeningPlugin)
    .run();

Animate the position (Transform::translation) of an Entity:

// Create a single animation (tween) to move an entity.
let tween = Tween::new(
    // Use a quadratic easing on both endpoints.
    EaseFunction::QuadraticInOut,
    // It takes 1 second to go from start to end points.
    Duration::from_secs(1),
    // The lens gives access to the Transform component of the Entity,
    // for the TweenAnimator to animate it. It also contains the start and
    // end values respectively associated with the progress ratios 0. and 1.
    TransformPositionLens {
        start: Vec3::ZERO,
        end: Vec3::new(1., 2., -4.),
    },
);

// Spawn an entity to animate the position of.
commands.spawn((
    Transform::default(),
    // Create a tweenable animation targetting the current entity. Without AnimTarget,
    // the target is implicitly a component on this same entity. The exact component
    // type is derived from the type of the Lens used by the Tweenable itself.
    TweenAnim::new(tween),
));

If the target of the animation is not a component on the current entity, then an AnimTarget component is necessary to specify that target. Note that AnimTarget is always mandatory for resource and asset animations.

#[derive(Resource)]
struct MyResource;

// Create a single animation (tween) to animate a resource.
let tween = make_tween::<MyResource>();

// Spawn an entity to own the resource animation.
commands.spawn((
    TweenAnim::new(tween),
    // The AnimTarget is necessary here:
    AnimTarget::resource::<MyResource>(),
));

This example shows the general pattern to add animations for any component, resource, or asset. Since moving the position of an object is a very common task, 🍃 Bevy Tweening provides a shortcut for it. The above example can be rewritten more concicely as:

commands
    // Spawn an entity to animate the position of.
    .spawn((Transform::default(),))
    // Create a new Transform::translation animation
    .move_to(
        Vec3::new(1., 2., -4.),
        Duration::from_secs(1),
        EaseFunction::QuadraticInOut,
    );

The move_to() extension is convenient helper for animations, which creates a Tween that animates the Transform::translation. It has the added benefit that the starting point is automatically read from the component itself; you only need to specify the end position. See the EntityCommandsTweeningExtensions extension trait defining helpers for other common animations.

§Ready to animate

Unlike previous versions of 🍃 Bevy Tweening, you don’t need any particular system setup aside from adding the TweeningPlugin to your App. In particular, per-component-type and per-asset-type systems are gone. Instead, the plugin adds a single system executing during the Update schedule, which calls TweenAnim::step_all(). Each TweenAnim acts as a controller for one animation, and mutates its target.

§Tweenables

🍃 Bevy Tweening supports several types of tweenables, building blocks that can be combined to form complex animations. A tweenable is a type implementing the Tweenable trait.

  • Tween - A simple tween (easing) animation between two values.
  • Sequence - A series of tweenables executing in series, one after the other.
  • Delay - A time delay. This doesn’t animate anything.

To execute multiple animations in parallel (like the Tracks tweenable used to do in older versions of 🍃 Bevy Tweening; it’s now removed), simply enqueue each animation independently. This require careful selection of individual timings though if you want to synchronize those animations.

§Chaining animations

Most tweenables can be chained with the then() operator to produce a Sequence tweenable:

let tween1 = Tween::new(
    // [...]
);
let tween2 = Tween::new(
    // [...]
);
// Produce a Sequence executing first 'tween1' then 'tween2'
let seq = tween1.then(tween2);

Note that some tweenable animations can be of infinite duration; this is the case for example when using RepeatCount::Infinite. If you add such an infinite animation in a sequence, and append more tweenables after it, those tweenables will never play because playback will be stuck forever repeating the first animation. You’re responsible for creating sequences that make sense. In general, only use infinite tweenable animations alone or as the last element of a sequence (for example, move to position and then rotate forever on self).

§TweenAnim

Bevy components, resources, and assets, are animated with the TweenAnim component. This component acts as a controller for a single animation. It determines the target component, resource, or asset, to animate, via an AnimTarget, and accesses the field(s) of that target using a Lens.

Because assets are typically shared, and the animation applies to the asset itself, all users of the asset see the animation. For example, animating the color of a ColorMaterial will change the color of all the 2D meshes using that material. If you want to animate the color of a single mesh, you need to duplicate the asset and assign a unique copy to that mesh, then animate that copy alone.

After that, you can use the TweenAnim component to control the animation playback:

fn my_system(mut anim: Single<&mut TweenAnim>) {
    anim.speed = 0.8; // 80% playback speed
}

§Lenses

The AnimTarget references the target (component, resource, or asset) being animated. However, only a part of that target is generally animated. To that end, the TweenAnim (or, more exactly, the Tweenable it uses) accesses the field(s) to animate via a lens, a type that implements the Lens trait and allows mapping a target to the actual value(s) animated.

For example, the TransformPositionLens uses a Transform component as input, and animates its Transform::translation field only, leaving the rotation and scale unchanged.

impl Lens<Transform> for TransformPositionLens {
    fn lerp(&mut self, mut target: Mut<Transform>, ratio: f32) {
        target.translation = self.start.lerp(self.end, ratio);
    }
}

Several built-in lenses are provided in the lens module for the most commonly animated fields, like the components of a Transform. Those are provided for convenience and mainly as examples. 🍃 Bevy Tweening expects you to write your own lenses by implementing the Lens trait, which as you can see above is very simple. This allows animating virtually any field of any component, resource, or asset, whether shipped with Bevy or defined by the user.

§Tweening vs. keyframed animation

🍃 Bevy Tweening is a “tweening” animation library. It focuses on simple animations often used in applications and games to breathe life into a user interface or the objects of a game world. The API design favors simplicity, often for quick one-shot animations created from code. This type of animation is inherently simpler than a full-blown animation solution, like bevy_animation, which typically works with complex keyframe-based animation curves authored via Digital Content Creation (DCC) tools like 3D modellers and exported as assets, and whose most common usage is skeletal animation of characters. There’s a grey area between those two approaches, and you can use both to achieve most animations, but 🍃 Bevy Tweening will shine for simpler animations while bevy_animation while offer a more extensive support for larger, more complex ones.

Re-exports§

pub use lens::Lens;

Modules§

lens
Collection of predefined lenses for common Bevy components and assets.

Structs§

AnimCompletedEvent
Event raised when a TweenAnim completed.
AnimTarget
Component defining the target of an animation.
AnimatedEntityCommands
Wrapper over an EntityCommands which stores an animation command.
CycleCompletedEvent
Event raised when an animation completed a single cycle.
Delay
A time delay that doesn’t animate anything.
Sequence
A sequence of tweenable animations played in order one after the other.
Tween
Single tweening animation description.
TweenAnim
Animation controller instance.
TweenResolver
Resolver for resources and assets.
TweeningPlugin
Plugin to register the 🍃 Bevy Tweening animation framework.

Enums§

AnimTargetKind
Enumeration of the types of animation targets.
AnimationSystem
Label enum for the systems relating to animations
EaseMethod
Describe how eased value should be computed.
PlaybackDirection
Direction a tweening animation is playing.
PlaybackState
Playback state of a TweenAnim.
RepeatCount
How many times to repeat a tweenable animation.
RepeatStrategy
Repeat strategy for animation cycles.
TotalDuration
Possibly infinite duration of an animation.
TweenState
Playback state of a Tweenable.
TweeningError
Errors returned by various animation functions.

Traits§

EntityCommandsTweeningExtensions
Extension trait for EntityCommands, adding animation functionalities for commonly used tweening animations.
IntoBoxedTweenable
Helper trait to accept boxed and non-boxed tweenables in various functions.
TweenCommand
Helper trait to abstract a tweening animation command.
Tweenable
Tweening animation description, either a single Tween or a collection of them.

Type Aliases§

BoxedTweenable
The dynamic tweenable type.