← View other resources
resource

Sine Waves make your game prettier

Spice up the visuals in your game using sine wave motion.
Mimpy
Lv. 26
· 3 min read · 2206 views
Boring This is a circle. It's not very impressive. It's pretty boring, even. If I want to add some life to this circle, I'm gonna need to make it animate. But I'm not an artist, how can I animate my circle?


Well, luckily I can spice up stuff in my project by making them move with code. Sine waves create a smooth back and forth motion that adds visual interest to pretty much any static image in your game. More visual interest means more engagement from the player. Sine waves can be used for all kinds of stuff ranging from titles and UI elements to background images to even characters!

1
The Math
The formula for a sine wave is as follows:
y = sin(x * 2pi / period) * amplitude + midpoint

Where:
y is the property we want to change
x is time (increasing constantly)
2pi is a mathematical constant (it's the circumference of a circle with radius 1)
period is how long one cycle of the sine wave takes
amplitude is how high up and down the sine wave goes

2
Code
In code, our sine wave is gonna look almost exactly like the math version. Let's make two functions that'll work as different variations of our sine wave. We'll pop this into a scr_sine script.

function sine_wave(time, period, amplitude, midpoint) {
    return sin(time * 2 * pi / period) * amplitude + midpoint;
}

function sine_between(time, period, minimum, maximum) {
    var midpoint = mean(minimum, maximum);
    var amplitude = maximum - midpoint;
    return sine_wave(time, period, amplitude, midpoint);
}

This first function accepts an amplitude and a midpoint. The second function accepts a minimum and a maximum. This second function is helpful for times when you want a sine wave to go between two specific numbers, instead of wanting it to bob around a number.

3
Examples

  1. A circle that bobs up and down nicely. Moving 64 pixels above and below 0, bobbing once every second.

    y = sine_wave(current_time / 1000, 1, 64, 0);
    Interesting!
  2. A ghost that fades in and out of sight, once every two seconds.

    image_alpha = sine_between(current_time / 1000, 2, 0, 1);
    Spooky
  3. A nice pendulum that swings 45 degrees back and forth around straight downwards (270 degrees). Swings once per second.

    image_angle = sine_wave(current_time / 1000, 1, 45, 270);
    Swingy
  4. A bouncy robo friend! Using two sine waves, you can really give a flat, non-animated character sprite some life!

    var time = current_time / 1000;
    image_yscale = sine_between(time, 1, 0.75, 1);
    image_angle = sine_wave(time, 2, 15, 0);
    Friendly


For each of my examples, I passed in current_time / 1000 as my time argument to measure in seconds, but you can use any units for time. Frames, milliseconds, points, position, feel free to get creative and use different stuff as a time measurement!