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 :frowning: (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.



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


and how do you change the speed and the direction of the triangle wave?

This post specifically talked about different shapes of specifically sine waves but you can make a version for any speed and height. See below

y = height * ((x/width - offset) % 1)
y = 2*math.abs(height * ((x/width - offset) % 1) - height/2) - height/2

You can change the direction by just making the width negative
Theres also a couple things you could mean by speed, but I assume you just mean how fast it goes up and down. This can be adjusted by changing the width. In case you meant actual speed you can just make offset change with time

1 Like

i assume the width is the speed minus the offset.
thanks tho!