1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
#![deny(
warnings,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications,
missing_docs
)]
//! Tweening animation plugin for the Bevy game engine
//!
//! 🍃 Bevy Tweening provides interpolation-based animation between ("tweening")
//! two values, for Bevy components and assets. Each field of a component or
//! asset can be animated via a collection or predefined easing functions,
//! or providing a custom animation curve. Custom components and assets are also
//! supported.
//!
//! # Example
//!
//! Add the tweening plugin to your app:
//!
//! ```no_run
//! use bevy::prelude::*;
//! use bevy_tweening::*;
//!
//! App::default()
//! .add_plugins(DefaultPlugins)
//! .add_plugins(TweeningPlugin)
//! .run();
//! ```
//!
//! Animate the position ([`Transform::translation`]) of an [`Entity`]:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_tweening::{lens::*, *};
//! # use std::time::Duration;
//! # fn system(mut commands: Commands) {
//! # let size = 16.;
//! // Create a single animation (tween) to move an entity.
//! let tween = Tween::new(
//! // Use a quadratic easing on both endpoints.
//! EaseFunction::QuadraticInOut,
//! // Animation time.
//! Duration::from_secs(1),
//! // The lens gives access to the Transform component of the Entity,
//! // for the Animator 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.),
//! },
//! );
//!
//! commands.spawn((
//! // Spawn an entity to animate the position of.
//! TransformBundle::default(),
//! // Add an Animator component to control and execute the animation.
//! Animator::new(tween),
//! ));
//! # }
//! ```
//!
//! Note that this example leverages the fact [`TweeningPlugin`] automatically
//! adds the necessary system to animate [`Transform`] components. However, for
//! most other components and assets, you need to manually add those systems to
//! your `App`.
//!
//! # System setup
//!
//! Adding the [`TweeningPlugin`] to your app provides the basic setup for using
//! 🍃 Bevy Tweening. However, additional setup is required depending on the
//! components and assets you want to animate:
//!
//! - To ensure a component `C` is animated, the
//! [`component_animator_system::<C>`] system must run each frame, in addition
//! of adding an [`Animator::<C>`] component to the same Entity as `C`.
//!
//! - To ensure an asset `A` is animated, the [`asset_animator_system::<A>`]
//! system must run each frame, in addition of adding an [`AssetAnimator<A>`]
//! component to any Entity. Animating assets also requires the `bevy_asset`
//! feature (enabled by default).
//!
//! By default, 🍃 Bevy Tweening adopts a minimalist approach, and the
//! [`TweeningPlugin`] will only add systems to animate components and assets
//! for which a [`Lens`] is provided by 🍃 Bevy Tweening itself. This means that
//! any other Bevy component or asset (either built-in from Bevy itself, or
//! custom) requires manually scheduling the appropriate system.
//!
//! | Component or Asset | Animation system added by `TweeningPlugin`? |
//! |---|---|
//! | [`Transform`] | Yes |
//! | [`Sprite`] | Only if `bevy_sprite` feature |
//! | [`ColorMaterial`] | Only if `bevy_sprite` feature |
//! | [`Style`] | Only if `bevy_ui` feature |
//! | [`Text`] | Only if `bevy_text` feature |
//! | All other components | No |
//!
//! To add a system for a component `C`, use:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_tweening::*;
//! # let mut app = App::default();
//! # #[derive(Component)] struct C;
//! app.add_systems(Update,
//! component_animator_system::<C>
//! .in_set(AnimationSystem::AnimationUpdate));
//! ```
//!
//! Similarly for an asset `A`, use the `asset_animator_system`. This is only
//! available with the `bevy_asset` feature.
//!
//! # 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.
//! - [`Tracks`] - A collection of tweenables executing in parallel.
//! - [`Delay`] - A time delay. This doesn't animate anything.
//!
//! ## Chaining animations
//!
//! Most tweenables can be chained with the `then()` operator to produce a
//! [`Sequence`] tweenable:
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_tweening::{lens::*, *};
//! # use std::time::Duration;
//! let tween1 = Tween::new(
//! // [...]
//! # EaseFunction::BounceOut,
//! # Duration::from_secs(2),
//! # TransformScaleLens {
//! # start: Vec3::ZERO,
//! # end: Vec3::ONE,
//! # },
//! );
//! let tween2 = Tween::new(
//! // [...]
//! # EaseFunction::QuadraticInOut,
//! # Duration::from_secs(1),
//! # TransformPositionLens {
//! # start: Vec3::ZERO,
//! # end: Vec3::new(3.5, 0., 0.),
//! # },
//! );
//! // Produce a Sequence executing first 'tween1' then 'tween2'
//! let seq = tween1.then(tween2);
//! ```
//!
//! # Animators and lenses
//!
//! Bevy components and assets are animated with tweening _animator_ components,
//! which take a tweenable and apply it to another component on the same
//! [`Entity`]. Those animators determine that other component and its fields to
//! animate using a _lens_.
//!
//! ## Components animation
//!
//! Components are animated with the [`Animator`] component, which is generic
//! over the type of component it animates. This is a restriction imposed by
//! Bevy, to access the animated component as a mutable reference via a
//! [`Query`] and comply with the ECS rules.
//!
//! The [`Animator`] itself is not generic over the subset of fields of the
//! components it animates. This limits the proliferation of generic types when
//! animating e.g. both the position and rotation of an entity.
//!
//! ## Assets animation
//!
//! Assets are animated in a similar way to component, via the [`AssetAnimator`]
//! component. This requires the `bevy_asset` feature (enabled by default).
//!
//! 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.
//!
//! ## Lenses
//!
//! Both [`Animator`] and [`AssetAnimator`] access the field(s) to animate via a
//! lens, a type that implements the [`Lens`] trait.
//!
//! Several predefined lenses are provided in the [`lens`] module for the most
//! commonly animated fields, like the components of a [`Transform`]. A custom
//! lens can also be created by implementing the trait, allowing to animate
//! virtually any field of any Bevy component or asset.
//!
//! [`Transform::translation`]: https://docs.rs/bevy/0.12.0/bevy/transform/components/struct.Transform.html#structfield.translation
//! [`Entity`]: https://docs.rs/bevy/0.12.0/bevy/ecs/entity/struct.Entity.html
//! [`Query`]: https://docs.rs/bevy/0.12.0/bevy/ecs/system/struct.Query.html
//! [`ColorMaterial`]: https://docs.rs/bevy/0.12.0/bevy/sprite/struct.ColorMaterial.html
//! [`Sprite`]: https://docs.rs/bevy/0.12.0/bevy/sprite/struct.Sprite.html
//! [`Style`]: https://docs.rs/bevy/0.12.0/bevy/ui/struct.Style.html
//! [`Text`]: https://docs.rs/bevy/0.12.0/bevy/text/struct.Text.html
//! [`Transform`]: https://docs.rs/bevy/0.12.0/bevy/transform/components/struct.Transform.html
use std::time::Duration;
use bevy::prelude::*;
use interpolation::Ease as IEase;
pub use interpolation::{EaseFunction, Lerp};
pub use lens::Lens;
#[cfg(feature = "bevy_asset")]
pub use plugin::asset_animator_system;
pub use plugin::{component_animator_system, AnimationSystem, TweeningPlugin};
pub use tweenable::{
BoxedTweenable, Delay, Sequence, Targetable, TotalDuration, Tracks, Tween, TweenCompleted,
TweenState, Tweenable,
};
pub mod lens;
mod plugin;
mod tweenable;
#[cfg(test)]
mod test_utils;
/// How many times to repeat a tween animation. See also: [`RepeatStrategy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepeatCount {
/// Run the animation N times.
Finite(u32),
/// Run the animation for some amount of time.
For(Duration),
/// Loop the animation indefinitely.
Infinite,
}
impl Default for RepeatCount {
fn default() -> Self {
Self::Finite(1)
}
}
impl From<u32> for RepeatCount {
fn from(value: u32) -> Self {
Self::Finite(value)
}
}
impl From<Duration> for RepeatCount {
fn from(value: Duration) -> Self {
Self::For(value)
}
}
/// What to do when a tween animation needs to be repeated. See also
/// [`RepeatCount`].
///
/// Only applicable when [`RepeatCount`] is greater than the animation duration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepeatStrategy {
/// Reset the animation back to its starting position.
Repeat,
/// Follow a ping-pong pattern, changing the direction each time an endpoint
/// is reached.
///
/// A complete cycle start -> end -> start always counts as 2 loop
/// iterations for the various operations where looping matters. That
/// is, a 1 second animation will take 2 seconds to end up back where it
/// started.
MirroredRepeat,
}
impl Default for RepeatStrategy {
fn default() -> Self {
Self::Repeat
}
}
/// Playback state of an animator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimatorState {
/// The animation is playing. This is the default state.
Playing,
/// The animation is paused in its current state.
Paused,
}
impl Default for AnimatorState {
fn default() -> Self {
Self::Playing
}
}
impl std::ops::Not for AnimatorState {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Self::Paused => Self::Playing,
Self::Playing => Self::Paused,
}
}
}
/// Describe how eased value should be computed.
#[derive(Clone, Copy)]
pub enum EaseMethod {
/// Follow `EaseFunction`.
EaseFunction(EaseFunction),
/// Linear interpolation, with no function.
Linear,
/// Discrete interpolation, eased value will jump from start to end when
/// stepping over the discrete limit.
Discrete(f32),
/// Use a custom function to interpolate the value.
CustomFunction(fn(f32) -> f32),
}
impl EaseMethod {
#[must_use]
fn sample(self, x: f32) -> f32 {
match self {
Self::EaseFunction(function) => x.calc(function),
Self::Linear => x,
Self::Discrete(limit) => {
if x > limit {
1.
} else {
0.
}
}
Self::CustomFunction(function) => function(x),
}
}
}
impl Default for EaseMethod {
fn default() -> Self {
Self::Linear
}
}
impl From<EaseFunction> for EaseMethod {
fn from(ease_function: EaseFunction) -> Self {
Self::EaseFunction(ease_function)
}
}
/// Direction a tweening animation is playing.
///
/// When playing a tweenable forward, the progress values `0` and `1` are
/// respectively mapped to the start and end bounds of the lens(es) being used.
/// Conversely, when playing backward, this mapping is reversed, such that a
/// progress value of `0` corresponds to the state of the target at the end
/// bound of the lens, while a progress value of `1` corresponds to the state of
/// that target at the start bound of the lens, effectively making the animation
/// play backward.
///
/// For all but [`RepeatStrategy::MirroredRepeat`] this is always
/// [`TweeningDirection::Forward`], unless manually configured with
/// [`Tween::set_direction()`] in which case the value is constant equal to the
/// value set. When using [`RepeatStrategy::MirroredRepeat`], this is either
/// forward (from start to end; ping) or backward (from end to start; pong),
/// depending on the current iteration of the loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TweeningDirection {
/// Animation playing from start to end.
Forward,
/// Animation playing from end to start, in reverse.
Backward,
}
impl TweeningDirection {
/// Is the direction equal to [`TweeningDirection::Forward`]?
#[must_use]
pub fn is_forward(&self) -> bool {
*self == Self::Forward
}
/// Is the direction equal to [`TweeningDirection::Backward`]?
#[must_use]
pub fn is_backward(&self) -> bool {
*self == Self::Backward
}
}
impl Default for TweeningDirection {
fn default() -> Self {
Self::Forward
}
}
impl std::ops::Not for TweeningDirection {
type Output = Self;
fn not(self) -> Self::Output {
match self {
Self::Forward => Self::Backward,
Self::Backward => Self::Forward,
}
}
}
macro_rules! animator_impl {
() => {
/// Set the initial playback state of the animator.
#[must_use]
pub fn with_state(mut self, state: AnimatorState) -> Self {
self.state = state;
self
}
/// Set the initial speed of the animator. See [`Animator::set_speed`] for
/// details.
#[must_use]
pub fn with_speed(mut self, speed: f32) -> Self {
self.speed = speed;
self
}
/// Set the animation speed. Defaults to 1.
///
/// A speed of 2 means the animation will run twice as fast while a speed of 0.1
/// will result in a 10x slowed animation.
pub fn set_speed(&mut self, speed: f32) {
self.speed = speed;
}
/// Get the animation speed.
///
/// See [`set_speed()`] for a definition of what the animation speed is.
///
/// [`set_speed()`]: Animator::speed
pub fn speed(&self) -> f32 {
self.speed
}
/// Set the top-level tweenable item this animator controls.
pub fn set_tweenable(&mut self, tween: impl Tweenable<T> + 'static) {
self.tweenable = Box::new(tween);
}
/// Get the top-level tweenable this animator is currently controlling.
#[must_use]
pub fn tweenable(&self) -> &dyn Tweenable<T> {
self.tweenable.as_ref()
}
/// Get the top-level mutable tweenable this animator is currently controlling.
#[must_use]
pub fn tweenable_mut(&mut self) -> &mut dyn Tweenable<T> {
self.tweenable.as_mut()
}
/// Stop animation playback and rewind the animation.
///
/// This changes the animator state to [`AnimatorState::Paused`] and rewind its
/// tweenable.
pub fn stop(&mut self) {
self.state = AnimatorState::Paused;
self.tweenable_mut().rewind();
}
};
}
/// Component to control the animation of another component.
///
/// The animated component is the component located on the same entity as the
/// [`Animator<T>`] itself.
#[derive(Component)]
pub struct Animator<T: Component> {
/// Control if this animation is played or not.
pub state: AnimatorState,
tweenable: BoxedTweenable<T>,
speed: f32,
}
impl<T: Component + std::fmt::Debug> std::fmt::Debug for Animator<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Animator")
.field("state", &self.state)
.finish()
}
}
impl<T: Component> Animator<T> {
/// Create a new animator component from a single tweenable.
#[must_use]
pub fn new(tween: impl Tweenable<T> + 'static) -> Self {
Self {
state: default(),
tweenable: Box::new(tween),
speed: 1.,
}
}
animator_impl!();
}
/// Component to control the animation of an asset.
///
/// The animated asset is the asset referenced by a [`Handle<T>`] component
/// located on the same entity as the [`AssetAnimator<T>`] itself.
#[cfg(feature = "bevy_asset")]
#[derive(Component)]
pub struct AssetAnimator<T: Asset> {
/// Control if this animation is played or not.
pub state: AnimatorState,
tweenable: BoxedTweenable<T>,
speed: f32,
}
#[cfg(feature = "bevy_asset")]
impl<T: Asset + std::fmt::Debug> std::fmt::Debug for AssetAnimator<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AssetAnimator")
.field("state", &self.state)
.finish()
}
}
#[cfg(feature = "bevy_asset")]
impl<T: Asset> AssetAnimator<T> {
/// Create a new asset animator component from a single tweenable.
#[must_use]
pub fn new(tween: impl Tweenable<T> + 'static) -> Self {
Self {
state: default(),
tweenable: Box::new(tween),
speed: 1.,
}
}
animator_impl!();
}
/// Trait to interpolate between two values.
/// Needed for color.
#[allow(dead_code)]
trait ColorLerper {
fn lerp(&self, target: &Self, ratio: f32) -> Self;
}
#[allow(dead_code)]
impl ColorLerper for Color {
fn lerp(&self, target: &Color, ratio: f32) -> Color {
let r = self.r().lerp(target.r(), ratio);
let g = self.g().lerp(target.g(), ratio);
let b = self.b().lerp(target.b(), ratio);
let a = self.a().lerp(target.a(), ratio);
Color::rgba(r, g, b, a)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::*;
struct DummyLens {
start: f32,
end: f32,
}
#[derive(Debug, Default, Component)]
struct DummyComponent {
value: f32,
}
#[cfg(feature = "bevy_asset")]
#[derive(Asset, Debug, Default, Reflect)]
struct DummyAsset {
value: f32,
}
impl Lens<DummyComponent> for DummyLens {
fn lerp(&mut self, target: &mut DummyComponent, ratio: f32) {
target.value = self.start.lerp(self.end, ratio);
}
}
#[test]
fn dummy_lens_component() {
let mut c = DummyComponent::default();
let mut l = DummyLens { start: 0., end: 1. };
for r in [0_f32, 0.01, 0.3, 0.5, 0.9, 0.999, 1.] {
l.lerp(&mut c, r);
assert_approx_eq!(c.value, r);
}
}
#[cfg(feature = "bevy_asset")]
impl Lens<DummyAsset> for DummyLens {
fn lerp(&mut self, target: &mut DummyAsset, ratio: f32) {
target.value = self.start.lerp(self.end, ratio);
}
}
#[cfg(feature = "bevy_asset")]
#[test]
fn dummy_lens_asset() {
let mut a = DummyAsset::default();
let mut l = DummyLens { start: 0., end: 1. };
for r in [0_f32, 0.01, 0.3, 0.5, 0.9, 0.999, 1.] {
l.lerp(&mut a, r);
assert_approx_eq!(a.value, r);
}
}
#[test]
fn repeat_count() {
let count = RepeatCount::default();
assert_eq!(count, RepeatCount::Finite(1));
}
#[test]
fn repeat_strategy() {
let strategy = RepeatStrategy::default();
assert_eq!(strategy, RepeatStrategy::Repeat);
}
#[test]
fn tweening_direction() {
let tweening_direction = TweeningDirection::default();
assert_eq!(tweening_direction, TweeningDirection::Forward);
}
#[test]
fn animator_state() {
let mut state = AnimatorState::default();
assert_eq!(state, AnimatorState::Playing);
state = !state;
assert_eq!(state, AnimatorState::Paused);
state = !state;
assert_eq!(state, AnimatorState::Playing);
}
#[test]
fn ease_method() {
let ease = EaseMethod::default();
assert!(matches!(ease, EaseMethod::Linear));
let ease = EaseMethod::EaseFunction(EaseFunction::QuadraticIn);
assert_eq!(0., ease.sample(0.));
assert_eq!(0.25, ease.sample(0.5));
assert_eq!(1., ease.sample(1.));
let ease = EaseMethod::Linear;
assert_eq!(0., ease.sample(0.));
assert_eq!(0.5, ease.sample(0.5));
assert_eq!(1., ease.sample(1.));
let ease = EaseMethod::Discrete(0.3);
assert_eq!(0., ease.sample(0.));
assert_eq!(1., ease.sample(0.5));
assert_eq!(1., ease.sample(1.));
let ease = EaseMethod::CustomFunction(|f| 1. - f);
assert_eq!(0., ease.sample(1.));
assert_eq!(0.5, ease.sample(0.5));
assert_eq!(1., ease.sample(0.));
}
#[test]
fn animator_new() {
let tween = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = Animator::<DummyComponent>::new(tween);
assert_eq!(animator.state, AnimatorState::default());
assert_eq!(animator.tweenable().progress(), 0.);
}
#[test]
fn animator_with_state() {
for state in [AnimatorState::Playing, AnimatorState::Paused] {
let tween = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = Animator::new(tween).with_state(state);
assert_eq!(animator.state, state);
// impl Debug
let debug_string = format!("{:?}", animator);
assert_eq!(
debug_string,
format!("Animator {{ state: {:?} }}", animator.state)
);
}
}
#[test]
fn animator_controls() {
let tween = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = Animator::new(tween);
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.stop();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.tweenable_mut().set_progress(0.5);
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.5);
animator.tweenable_mut().rewind();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.tweenable_mut().set_progress(0.5);
animator.state = AnimatorState::Playing;
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.5);
animator.tweenable_mut().rewind();
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.stop();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
}
#[test]
fn animator_speed() {
let tween = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = Animator::new(tween);
assert_approx_eq!(animator.speed(), 1.); // default speed
animator.set_speed(2.4);
assert_approx_eq!(animator.speed(), 2.4);
let tween = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = Animator::new(tween).with_speed(3.5);
assert_approx_eq!(animator.speed(), 3.5);
}
#[test]
fn animator_set_tweenable() {
let tween = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = Animator::new(tween);
let tween2 = Tween::<DummyComponent>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(2),
DummyLens { start: 0., end: 1. },
);
animator.set_tweenable(tween2);
assert_eq!(animator.tweenable().duration(), Duration::from_secs(2));
}
#[cfg(feature = "bevy_asset")]
#[test]
fn asset_animator_new() {
let tween = Tween::<DummyAsset>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = AssetAnimator::new(tween);
assert_eq!(animator.state, AnimatorState::default());
let tween = animator;
assert_eq!(tween.tweenable().progress(), 0.);
}
#[cfg(feature = "bevy_asset")]
#[test]
fn asset_animator_with_state() {
for state in [AnimatorState::Playing, AnimatorState::Paused] {
let tween = Tween::<DummyAsset>::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = AssetAnimator::new(tween).with_state(state);
assert_eq!(animator.state, state);
// impl Debug
let debug_string = format!("{:?}", animator);
assert_eq!(
debug_string,
format!("AssetAnimator {{ state: {:?} }}", animator.state)
);
}
}
#[cfg(feature = "bevy_asset")]
#[test]
fn asset_animator_controls() {
let tween: Tween<DummyAsset> = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = AssetAnimator::new(tween);
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.stop();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.tweenable_mut().set_progress(0.5);
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.5);
animator.tweenable_mut().rewind();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.tweenable_mut().set_progress(0.5);
animator.state = AnimatorState::Playing;
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.5);
animator.tweenable_mut().rewind();
assert_eq!(animator.state, AnimatorState::Playing);
assert_approx_eq!(animator.tweenable().progress(), 0.);
animator.stop();
assert_eq!(animator.state, AnimatorState::Paused);
assert_approx_eq!(animator.tweenable().progress(), 0.);
}
#[cfg(feature = "bevy_asset")]
#[test]
fn asset_animator_speed() {
let tween: Tween<DummyAsset> = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = AssetAnimator::new(tween);
assert_approx_eq!(animator.speed(), 1.); // default speed
animator.set_speed(2.4);
assert_approx_eq!(animator.speed(), 2.4);
let tween: Tween<DummyAsset> = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let animator = AssetAnimator::new(tween).with_speed(3.5);
assert_approx_eq!(animator.speed(), 3.5);
}
#[cfg(feature = "bevy_asset")]
#[test]
fn asset_animator_set_tweenable() {
let tween: Tween<DummyAsset> = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(1),
DummyLens { start: 0., end: 1. },
);
let mut animator = AssetAnimator::new(tween);
let tween2 = Tween::new(
EaseFunction::QuadraticInOut,
Duration::from_secs(2),
DummyLens { start: 0., end: 1. },
);
animator.set_tweenable(tween2);
assert_eq!(animator.tweenable().duration(), Duration::from_secs(2));
}
}