How to use Cos and Sin

Version française: https://devforum.roblox.com/t/comment-utiliser-cos-et-sin/1660043

This tutorial will explain you how to use cos and sin inside of a Roblox experience.
In Roblox, you can access cos and sin with the math.cos() and math.sin() functions respectively.

What are cos and sin

Basically, cos and sin are mathematical functions, they take a number and give another, they also have curves, which help visualize how they work:

Cos Curve:
image

Sin Curve:
image

Those two functions are used in geometry, more specifically in circles, this is why you see degrees and radians in those curves.

If you examine the curves, you can notice the cos and sin are very similar, the only difference in those two curves is that the sin curve is basically the cos curve but offset by 90 degrees or pi/2.

What are their uses

A circle is 360 degrees or pi*2, a circle always starts on the right, and progresses counter-clockwise

As you can see on the circle, I have drawn one green line and one red line, the green line is the X axis and the red line is the Y axis.

Why axis in a circle? Because circles have a radius, in this case, the radius is 1, the radius is the length from the center of the circle to any extremities.

If you come back to the curves, you can see the curves Y value is between -1 and 1, meaning that when given a value in radians, the cos and sin functions will return a value between -1 and 1.

(Since Roblox’s cos and sin functions need radians as arguments, example will only be done with radians.)
For example, cos(pi) is equal to -1, because if you treat the circle as a grid with coordinates, and try to see where pi is on the green line, you can see it’s on the opposite side of where the circle starts.

Another example: cos(pi*0.75) is equal to -0.707.

Basically, cos gives you the ability to obtain a value between -1 and 1 by inputting a point on the circle as a radians.

As for sin, it’s the same thing, except, instead of getting a value on the X axis, you get a value on the Y axis.

For example, sin(pi*2) is equal to 0, it’s at the start of the circle, on the right, so the Y axis value is 0.

Now, what if I wanted to do the opposite? What if I wanted to obtain a value in radians based on an X or Y value that is between -1 and 1?

There’s arc cos and arc sin functions, which are the same but do the opposite, if you give them a value between -1 and 1, they will return a value in radians on the circle.
(On Roblox, you can access these functions with math.acos() and math.asin())

What are their practical uses

With cos and sin, we are working with circles, which means, you can accurately position objects in a circular or elliptic shape.

For example, let’s say I wanted to place 7 parts so that they shape a circle.

for i = 1, 7 do
	local formula = i * ((math.pi*2)/7)
	local position = Vector3.new(math.cos(formula) * 5, 5, math.sin(formula) * 5)
	
	local part = Instance.new("Part")
	part.Anchored = true
	part.Size = Vector3.new(1, 1, 1)
	part.Position = position
	part.Parent = workspace
end

This is the result you should get:

First, we create a for loop, it will run 7 times.
We then create a formula, the value of this formula is in radians, because we want to do a full circle, we go from 0 to 360 degrees in a progressive way, for example, if i is 1, then formula will be equal to around 51 degrees.

We have the position on the circle, now, based on that value, we want an X and Y value, so we will be using the cos and sin functions in a Vector3.new function, we want the circle to face upwards, so we’re using the cos function on the X axis and the sin function on the Z axis.

Remember, cos and sin are always used in a circle with a radius of 1, meaning we need to multiply the value cos and sin by the radius wanted, in this case, the parts will be away from the center by 5 studs.

Another interesting use of the cos and sin functions is for tweening parts. for example, if you wanted to make a floating crystal, you could do the following:

local part = Instance.new("Part")
part.Anchored = true
part.Size = Vector3.new(3, 5, 3)
part.Parent = workspace

local alpha = 0

game:GetService("RunService").Heartbeat:Connect(function(delta)
	alpha += delta
	part.CFrame = CFrame.new(0, 5 + math.sin(alpha), 0)
end)

This will give you a part that floats very smoothly and looks nicely animated.
alpha keeps going upwards, by 1 per second, the delta argument of the Heartbeat function is the time passed since the last frame.

This means alpha can be used as a radians, meaning the part will do a full cycle in pi seconds (about 3.14 seconds.)

That is all, I really hope this tutorial will allow you to understand how to use these two functions to give great spice to the visuals in your game, and make your life as a scripter easier.

64 Likes

Its amazing that someone was able to create a tutorial on how Cosine and Sine works in scripting.

I’m very familiar with Sine, Cosine, and Tangent since I’m currently taking a math course on my school that has a unit for it.

In other words, thank you for making a tutorial on this! I never knew that Sine and Cosine applied to Roblox Development nor did I know that

math.cos and math.sin

existed.

10 Likes

We can simplify this

for i = 1,7 do
local formula = math.pi*2/7*i
local x = math.cos(formula) * 10 -- radius
local z = math.sin(formula) * 10 -- radius again
local part = Instance.new("Part")
	part.Anchored = true
	part.Size = Vector3.new(1, 1, 1)
	part.Position = Vector3.new(x,5,z)
	part.Parent = workspace
task.wait()
end

Either way, good tutorial

2 Likes

That doesn’t look any more “Simplified” than the original, it actually looks more complicated.

2 Likes

oh really?
Compare this

With this

I think you think it’s complicated because i didn’t add any spaces in the formula

No…? The first method looks better since everything isn’t cluttered and i isn’t at the end, but at the front which in general looks way better, and that you split position up to two seperate variables called x and z.

Here’s a much better explanation of cos and sin:

(Source: Wikipedia Commons)

5 Likes

indeed. I dont understand a single thing here.

θ (Theta) is the number you pass to math.sin / math.cos. Then from there you can follow the illustration to figure out other things.

true. I couldn’t get a thing. Very true

1 Like

Noice ! I learned that before learn it in school

2 Likes

Well, theta (θ) is the angle you pass to the function, in radians. The lines (annotated with things like “cos” and “sin”) are the values you get out of it. ie calling math.cos(angle) gives you the blue line.

The center of the circle is 0, positive values are up/right, negative is down/left. The circle has a radius of 1.

1 Like

I definitely think you need some knowledge before to understand cosine and sine, but
this explain everything easier and more understandble then most video out on the internet.

1 Like

I love sin, it’s like one of my favorite math functions of all time.
It’s SO GOOD for things like procedural animations due it’s natural and curvy behavior.

You can use it for things like head bobbing in games, leg movement, you can animate the legs of a mechsuit with it.
Almost anything can be animated using sine waves, whether it’s for making things move u and down, left and right, looping in a circle.

By stacking multiple sines onto each other with different frequencies and amplitudes, more advanced and complicated yet still natural-looking movement can be achieved.
If you’re too lazy to animate something, just slap a sin() onto it and you’re all good.

If I recall, sin(), cos() and tan() can also be used to calculating angles or something on triangles but I forgot how exactly that worked, I would greatly appreciate if someone could explain me or refresh my mind on that.

1 Like

Basic Trigonometry - Resources / Community Tutorials - Developer Forum | Roblox

1 Like

Most of these functions, particularly ones like cosecant and versine are really useless. the basic trigonometrical functions are the most useful.

SOHCAHTOA is the acronym to use:
Sine is Opposite over Hypotenuse - SOH (S = O / H)
Cosine is Adjacent over Hypotenuse - CAH (C = A / H)
Tangent is Opposite over Adjacent - TOA (T = O / A)

Now, this doesn’t really do much. How do you use it? Well, let’s say we have a right - angled triangle and want to find out the length of one side, assuming we have the measure of an angle and another side’s length. First, label the sides - the one Opposite to the angle, the Hypotenuse and the one Adjacent to the angle. Secondly, plug in the right formula and voila, all done!
For example, we want to find X.
image
Labelling everything, we get that X is the adjacent and that 13 is the hypotenuse. We don’t need to label the opposite since we don’t know and don’t need to find out what it is. So, looking at our formulas, we need to use cosine because we have the hypotenuse’s length and want to find out the adjacent’s length. So, the formula is Cosine is Adjacent over Hypotenuse. Rearranging, the adjacent’s length is hypotenuse’s length multiplied by the cosine of the angle. Plugging it in, we get:

x = cos(60) x 13

which is 6.5cm. Yay!

What about angles? Let’s try:
image
Here, the sides have been labelled for us. But when we use the right function, tan, we run into a problem. tan(x) = 5/7 is a big problem because we can’t get rid of the big tan stuck in the way! If only we could remove it…
We can! We can use tan−1 (written as tan to the power of -1, said as “arctan”). We solve to get x = tan-1(5/7), which is 35.5 degrees! Yay!

Cosine is the exact same as sine, except offset by π/2 to the right. This is why it is known as complementary to sine.
You might notice that tan is completely different to both of these and doesn’t follow a “curve” like structure. I would steer clear of tan for animation. Just take a look at this, lol:

Sine and cosine are rather rigid too. Here are some ways to adapt them to fit your needs. First, a quick crash course on waves:
image
I’ll show you how to manipulate wavelength and amplitude, as well as offset.
For reference, here is the original:

  1. Changing the wavelength
    Simply multiply the x by a coefficient.
  2. Changing the amplitude
    All you need to do is multiply the whole function by a coefficient.
  3. Changing the offset on the Y axis
    Just add a number on to the end of the whole function.
  4. Changing the offset on the X axis
    Just add a number on to the end inside the sine function.

Hope this helped!

1 Like

Thank you! Also dayum that name is a mouthful.

One of the reasons I want to learn how to use sin/cos/tan functions is because Roblox doesn’t have polygon objects yet and I’m figuring out how I can size and CFrame 2 wedges to form a triangle for things like procedural terrain and whatnot.

Or use them to calculate how much I have to rotate a player’s neck to make the head look at a certain point in space.

I know plenty of math, though formulas and reading certain symbols sometimes still go a bit over my head.
I love math and maybe I have a thing for it due being autistic, though I struggle with some concepts unless properly explained with simple visuals and whatnot and why X does Y or why we need Z in the equation.

1 Like

Apologies, I got quite carried away…
Trigonometry is really, really useful when it’s needed.

1 Like

It’s fine, I find your explanations very useful and interesting to read!
I know some basics of sine and cosine since of course I use it a lot for procedural stuff, animating things and making effects with code.

Though I have rarely applied it to trigonometry before, it’s a subject I haven’t really gotten in school before in my country.
I learn most things at home to be honest and from seeing other game developers apply it in various ways and explaining how it works.

I feel like trigonometry can also be really useful in game development, I just have rarely used it and usually find my way with look vectors for problems like making a player’s head move.
Most of the time simple CFrame math and the use of directional vectors solves the issue.

Though, maybe I can optimize code or make some functions faster and use less CPU by using trigonometry and leaving out some of the unnecessary CFrame math?

1 Like