Skip to content

Instantly share code, notes, and snippets.

@sudara
Created October 22, 2024 20:00
Show Gist options
  • Select an option

  • Save sudara/5a055402e050ec7e9fcbbd04f057648b to your computer and use it in GitHub Desktop.

Select an option

Save sudara/5a055402e050ec7e9fcbbd04f057648b to your computer and use it in GitHub Desktop.
JUCE Animator Wrapper
#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;
});
}
};
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