Sine Waves make your game prettier
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!
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
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.
-
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);
-
A ghost that fades in and out of sight, once every two seconds.
image_alpha = sine_between(current_time / 1000, 2, 0, 1);
-
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);
-
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);
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!