Unity - Creating circular movement with sin and cos
Movement in games is exciting. No, really. I’m not kidding. It just a question of how you let the player (or the enemy) move. Let’s say you have an enemy which randomly decides to approach you in a circular way instead of in a straight line. Exciting, huh?
Now then, how can we achieve something like that? The answer is with math! The one subject at school probably nobody liked... But no worries, we won’t need any complicated stuff, just the sin and cos graphs and functions.
Let’s get started!
I. What even is a sin wave?
In a nutshell, a sin wave is ping-ponging between 1 and -1 (on the y-axis) over time (the x-axis).
II. Manipulating the y-axis movement with sin
As said and shown, a typical sin(x) wave goes up and down in one amplitude. Let’s just use that for the y-axis movement!
To do that, we need three local variables, which will be the movement Vector3.
x and z seem logical. We don’t want to manipulate them, so we leave them alone with their values.
Let’s take look at what this code does in Unity:
The player moves up and down continuously, exactly like in a sin wave!
Let’s tweak the code a bit! What if we also add some data for the frequency and the amplitude?
- Increasing the amplitude will change the y-axis - the values the graph is ping-ponging between - value on the sin(x) graph.
- Increasing the frequency will change how wide-stretched or far-squeezed the sin(x) wave is.
III. Manipulating the x-axis movement with cos
Let’s change the code shown above a bit and adapt it to x-axis movement with cos:
This will create the following movement scheme:
Amplitude and frequency can still be changed; also shown in the GIF below!
IV. Creating circular movement
Combining both, sin and cos, will create a circular movement!
And that’s about it for todays article!