animation improvemenets

This commit is contained in:
Jorijn van der Graaf 2025-11-26 00:24:23 +01:00
commit f842a445d7
2 changed files with 13 additions and 13 deletions

View file

@ -24,8 +24,7 @@ int main() {
element.UpdatePosition(window); element.UpdatePosition(window);
Animation<std::tuple<std::int_fast32_t>> anim({ Animation<std::tuple<std::int_fast32_t>> anim({
{std::chrono::seconds(0), FractionalToMapped(-0.5)}, {std::chrono::seconds(5), FractionalToMapped(-0.5), FractionalToMapped(1.5)},
{std::chrono::seconds(5), FractionalToMapped(1.5)}
}); });
anim.Start(std::chrono::high_resolution_clock::now()); anim.Start(std::chrono::high_resolution_clock::now());
@ -34,7 +33,7 @@ int main() {
std::tuple<std::int_fast32_t> value = anim.Play(time.now); std::tuple<std::int_fast32_t> value = anim.Play(time.now);
element.anchorX = std::get<0>(value); element.anchorX = std::get<0>(value);
element.UpdatePosition(window); element.UpdatePosition(window);
if(anim.currentFrame == anim.keyframes.size()-1) { if(anim.currentFrame == anim.keyframes.size()) {
anim.Start(time.now); anim.Start(time.now);
} }
window.LogTiming(); window.LogTiming();

View file

@ -53,7 +53,8 @@ namespace Crafter {
export template <typename T> export template <typename T>
struct Keyframe{ struct Keyframe{
std::chrono::duration<double> duration; std::chrono::duration<double> duration;
T values; T startValues;
T endValues;
}; };
export template <typename T> export template <typename T>
@ -67,27 +68,27 @@ namespace Crafter {
startedAt = time; startedAt = time;
} }
T Play(std::chrono::time_point<std::chrono::high_resolution_clock> time) { T Play(std::chrono::time_point<std::chrono::high_resolution_clock> time) {
std::chrono::duration<double> elapsed = time - startedAt; // elapsed time since animation started std::chrono::duration<double> elapsed = time - startedAt;
std::chrono::duration<double> accumulated(0); std::chrono::duration<double> accumulated(0);
for (std::uint_fast32_t i = currentFrame; i < keyframes.size() - 1; ++i) { for (std::uint_fast32_t i = currentFrame; i < keyframes.size(); ++i) {
accumulated += keyframes[i+1].duration; accumulated += keyframes[i].duration;
if (elapsed < accumulated) { if (elapsed < accumulated) {
std::chrono::duration<double> frameStartTime = accumulated - keyframes[i+1].duration; std::chrono::duration<double> frameStartTime = accumulated - keyframes[i].duration;
auto t = (elapsed - frameStartTime) / keyframes[i+1].duration.count(); auto t = (elapsed - frameStartTime) / keyframes[i].duration.count();
currentFrame = i; currentFrame = i;
return LerpTuple( return LerpTuple(
keyframes[i].values, keyframes[i].startValues,
keyframes[i + 1].values, keyframes[i].endValues,
t.count() t.count()
); );
} }
} }
// If we get here, we're past the last keyframe // If we get here, we're past the last keyframe
currentFrame = keyframes.size() - 1; currentFrame = keyframes.size();
return keyframes.back().values; return keyframes.back().endValues;
} }
}; };
} }