⭐️ In this tutorial we will learn how to use sin
to create movement!
Sine Waves by Carson Kompon (@URL)
Hello Sin Circle
The function sin
is very useful because if you feed it time t()
it will grow and shrink and grow and shrink forever.
The value fluctuates from -1 to 1 to -1 to 1.
If we want a bigger value we can multiply it to get a bigger range for example -10 to 10:
10 * sin(t())
So if we use sin
for the size of a circle, the circle will grow and shrink.
Note that half the time we won’t see the cirlce when the size is negative.
Fast forward and Slow motion
The circle is moving too fast!!
We can slow and speed up time by dividing or multiplying it.
So let’s change code to be time = t() / 2
Shifting the range
What if we want our circle to start from a positive size, let’s say go from 10 to 30?
If we add 1 to sin, instead of -1 to 1 we will get 0 to 2 because -1 + 1 = 0
and 1 + 1 = 2
So let’s change our code to be:
s = sin(time)+1
If we divide this by 2 we will get a nice 0 to 1 range:
s = (sin(time)+1)/2
Now that we have 0 to 1 we can easily get the range 10 to 30.
Let’s make the size go from 0 to 20 by multiplying s
by 20:
size = s*20
.
And then add 10 to make it from from 10 to 30:
size = 10 + s*20
Exercise 🍓
Can you mofiy the code to make the circle change color over time. From red to pink?
Movement with sin
Similar to how we change scale, we can change position using sin
and get a looping animation.
For example if we shift the sin
range to be from 20 to 100 and pass it as the x and y position of a circle, it will move diagnally in a loop:
Spinning with sin and cos!
Something cool about sin
and it’s sibling cos
is that they can create circular motion!
If you set the x position of a circle to cos
and the y pos to sin
you will see it spin in a circle
x = center + radius * cos(time)
y = center + radius * sin(time)
Note that you can collapse all the math and get the same visual with just a few rows of code:
Exercise 🍓
Can you make a solar system or another cool animation using sin and cos?
Next
Appendix
Resources