I have seen math.cos and math.sin in a lot of scripts that use view bobbing. As of now, I am trying to make my FPS gun have a walking animation, but right now all it does is just move left and right with no upper animation.
I believe I need to know what math.cos and math.sin means before I can start finishing the walking animation.
Can anyone give me a brief explanation of what math.cos and math.sin is so I can understand it better? I already know what it is used for, but I don't know how to utilize it in scripting locally. I don't need any code answers, just a simple explanation of what it does. (the wiki didn't help)
Well, math.sin
and math.cos
are both trigonometry.
math.sin
will return values between 1 and -1 when you input a number between 0.5pi (90 degrees) and 1.5pi (270 degrees) and back to 2.5 pi (450 degrees).
math.cos
will return values between 1 and -1 when you input a number between 0pi (0 degrees) and 1pi (180 degrees) and back to 2pi (360 degrees).
We will use the following to show you what you would get with both functions:
0 degrees : 0 pi
90 degrees : 0.5 pi
180 degrees : 1 pi
270 degrees : 1.5 pi
sin 0 pi = 0
sin 0.5 pi = 1
sin 1 pi = 0
sin 1.5 pi = -1cos 0 pi = 1
cos 0.5 pi = 0
cos 1 pi = -1
cos 1.5 pi = 0
What this means, as you see is, you get different outputs even when you put in the same numbers, this is because cosine leads by 90 degrees .
If we put this into a practical coding situation, we need to wrap it inside a steppedloop then put the double value inside of the functions; as shown:
game:GetService("RunService").Stepped:Connect(function(double) --double means: starting at 0 then adding step onto it each time it runs print("step : " .. tostring(double) .. " math.sin : " .. tostring(math.sin(double))) print("step : " .. tostring(double) .. " math.cos : " .. tostring(math.cos(double))) end)
You'll notice, if you run this , they print different values, but both cycle through 1 and -1.
There are somethings we can change though: the amplitude and the wavelength. If you do math.sin(double*math.pi*2)
, you'll notice that it cycles through 1 and -1 every second. This is the wavelength. If you do 2*math.sin(double*math.pi*2)
you'll notice that it cycles through 2 and -2 every second, this is called amplitude.
As shown through an example:
amplitude = 10 --the minimum and maximum value becomes -10 and 10. wavelength = (math.pi * 2) / 5 --the '5' means it takes 5 seconds it takes to cycle. game:GetService("RunService").Stepped:Connect(function(double) print(amplitude * math.sin(double * wavelength)) end)
Then plug these into a Vector3 or a CFrame, to get the "breathing effect".
I hope this helped you understand math.sin
and math.cos
, and if it did, please accept this answer. :)