Zig NEWS

Mason Remaley
Mason Remaley

Posted on

A Zig Easing/Tweening Library for Game Dev

Lerp, or linear interpolation, is a convenient way to animate stuff in games without having to store much state:

const position = lerp(start, end, time);
Enter fullscreen mode Exit fullscreen mode

This will move position linearly from start to end as time moves from 0 to 1.

Unfortunately, linear motion often appears robotic and unnatural. In fact--even a cartoony robot should overshoot and rattle a bit, right?

Thankfully there's an easy fix. You don't have to give up lerp, you can just play with the t value that you pass in:

Video of an asteroid moving back and forth as if it was a spring

The pictured asteroid is being linearly interpolated, but the t value is being modified by an elastic easing function causing it to act like a spring:

const position = lerp(start, end, elasticOut(t, .{}));
Enter fullscreen mode Exit fullscreen mode

Probably not the right way to move an asteroid, but pretty nifty for a one liner right?

Functions that play with a lerp’s t value are called “easing functions”, you can find visualizations for many commonly used easing functions on easings.net.

easing.net's easing functions

It’s nice to have a bunch of these on hand to pick from, so I just published a Zig library of all the popular ones. The stylized ones are all by Robert Penner and have been widely used since the days of flash.

You can check out the library on GitHub, and the full write up on my blog.

If you find this useful, consider signing up for my newsletter!

Top comments (0)