-
-
Save sudara/5a055402e050ec7e9fcbbd04f057648b to your computer and use it in GitHub Desktop.
JUCE Animator Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include "juce_animation/juce_animation.h" | |
| class Animation | |
| { | |
| public: | |
| explicit Animation (juce::Component& c) : component (c) {} | |
| float currentPosition = 0; | |
| bool isAnimating = false; | |
| void springTo (const float nextPosition, const int durationMs) | |
| { | |
| if (isAnimating) | |
| return; // debounce | |
| animator = defaultAnimator (nextPosition, durationMs) | |
| .withEasing (juce::Easings::createSpring (juce::SpringEasingOptions().withFrequency (1).withAttenuation (6.0).withExtraAttenuationRange (.85))) | |
| .build(); | |
| updater.addAnimator (animator); | |
| animator.start(); | |
| } | |
| void easeTo (const float nextPosition, const int durationMs) | |
| { | |
| animator = defaultAnimator (nextPosition, durationMs).withEasing (juce::Easings::createEaseOut()).build(); | |
| updater.addAnimator (animator); | |
| animator.start(); | |
| } | |
| private: | |
| float lastPosition = 0; | |
| juce::Component& component; | |
| juce::VBlankAnimatorUpdater updater { &component }; | |
| juce::Animator animator = juce::ValueAnimatorBuilder {}.build(); | |
| juce::ValueAnimatorBuilder defaultAnimator (float nextPosition, int durationMs) | |
| { | |
| return juce::ValueAnimatorBuilder {} | |
| .withDurationMs (durationMs) | |
| .withValueChangedCallback ([this, nextPosition] (auto value) { | |
| isAnimating = true; | |
| currentPosition = juce::makeAnimationLimits (lastPosition, nextPosition).lerp (value); | |
| component.repaint(); | |
| }) | |
| .withOnCompleteCallback ([this]() { | |
| isAnimating = false; | |
| lastPosition = currentPosition; | |
| }); | |
| } | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ExampleComponent : public juce::Component | |
| { | |
| public: | |
| void mouseDown (const juce::MouseEvent& e) override | |
| { | |
| animation.springTo (e.x, 250); | |
| } | |
| void paint (juce::Graphics& g) override | |
| { | |
| g.drawRoundedRectangle (animation.currentPosition, 0.f, 50.f, 50.f, 2, 2); | |
| } | |
| private: | |
| Animation animation { *this }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment