Essential Game Maths: Sine Waves

How are Sine Waves useful?

Sine waves is a fascinating mathematical phenomenon. They are useful for repeating behaviours and animating things over time – simply use the amount of seconds passed since started the game as input for sin function. 

Because of their simple organic nature, they’re used in many different aspects of development such as making waves in the ocean, moving around enemies or generating sound, etc.


What is a Sine Wave?

A repeating function that takes any value x as an input and output some value y.  The function oscillates between 1 and -1: As inserting value of x increase in size, the resulting y value smoothly goes from 0 – 1 to  0 – (-1) then back to 0.

circle_cos_sinUnit circle with hypothenuse – the angle in the left hand corner of the triangle is the x value to input into the function, the y value is the y coordinate of the upper corner of the triangle. As angle goes above 180 degrees the y becomes -1

Because the total number of degree is 360: function will repeat in intervals of exactly 360.

NOTE: must decide what unit of measurement to use(degrees/radians) because it uses an angle as input. The only difference – instead of going from 0 degrees to 360, the angle goes from 0 radians to 2pi radians.


Practical examples of using sine waves in games:

a looping hover animation for a save point by setting its y position as the input:

Position.y = sin(t) where t is time, starting with the y position of 0 and then smoothly moving up and down as time goes by.

To increase the speed of animation: multiply time variable with a speed multiplier. position.y = sin(t * 2) makes the animation go twice as fast.

To influence how far it moves up and down: multiply the entire function sine of t by a number. position.y = 2 * sin(t) makes the object move 2 units up and 2 units down

Moving a game object around its up axis infinitely in  Unity:
gameObject.transform.Translate(Vector3.up * Mathf.Cos(Time.timeSinceLevelLoad));

Further Reading: