# Different Sine-Waves/Wave-Forms (Triangle,Square,Sawtooth,Etc)

Hello Dev-Forum! I was wondering if it was possible to have different types of sine waves. Currently there is only 1 type of sine that I know of, the standard sine wave.
This can be achieved via math.sin(),math.cos().
The problem is in the fact that, well, that’s all there is (That I know of)

I’ve tried to achieve a simple triangle waveform by constantly changing a number positively, then start going negative once it reaches a maximum amount.
While this works, it feels mediocre when looking back at the code and I feel like there is a simpler and more professional way to go about this.

If you must, please prove me as an idiot! I’m hoping this will help a lot of people looking for the same thing.

-ZonK

1 Like

You can make some nice waves using some fancy math tricks

Below are the formulas:

And their Lua equivalents:

``````--sine wave
y = math.sin(x)

--square wave
y = math.sign(math.sin(x))

--sawtooth wave
y = x % (2*math.pi) * 1/math.pi - 1

--triangle wave
y = 2 * math.abs((x-math.pi/2) % (2*math.pi) * 1/math.pi - 1) - 1

``````

Some are pretty simple, some are not simple at all
Sine and square are pretty self explanatory, math.sign returns 1 if the input is positive, -1 if the input is negative, making a square like pattern

The sawtooth basically just gets the distance from the closest multiple of 2π on the negative side (what the modulus/remainder operation does) of y=x, and does some manipulation to it to get it positioned correctly as if it were a proper sawtooth wave
(The raw “closest multiple” graph shown below next to a normal sine wave)

You can see how it simply has to be repositioned/resized a bit to make it work nicely

The triangle wave is just the absolute value of the sawtooth wave, so its always positive
It is again rearranged a tiny bit to make it look like a proper triangle wave which is why theres all of the extra math around the modulus
(The raw “absolute value of sawtooth” graph is shown below next to the normal sawtooth graph)

You can once again see how it just has to be repositioned a bit, which is where the weird 2* and -1 come from

Hopefully this is helpful, I can try to explain anything if you need

7 Likes