How To Draw A Sine Wave

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Supatier

I’m thinking of drawing lines like python’s matplotlib.
My best bet is to use a function to get points (samples) and then set the resolution.

:bust_in_silhouette: Reply From: rolfpancake

It depends on your needs but I would go with drawing lines. Take a look at the Custom drawing in 2D tutorial if you are not familiar with the drawing methods.

Here is a little sample project I made in like 15 minutes:
Project files on mega.nz

Nodes used
https://i.imgur.com/7k9hNV5.png

Code written

extends Node2D

onready var a = 1
onready var b = 1
onready var c = 1

func ready():
	update()

func _draw():
	for i in range(1000):
		draw_line(Vector2(a*i, b*sin(c*i)), Vector2(a*(i+1), b*sin(c*(i+1))), ColorN("slateblue"), 1)

func _on_a_slider_value_changed( value ):
	a = value
	update()
	
func _on_b_slider_value_changed( value ):
	b = value
	update()
	
func _on_c_slider_value_changed( value ):
	c = value
	update()

What it looks like
https://media.giphy.com/media/xThtapBASCcpYEweDm/giphy.gif
(Gifv on Imgur)

Just what I’ve been looking for. But whats the third slider for? amplitude?

Supatier | 2018-02-06 12:45

I just added it to make it more random. Didn’t thought about its mathematical meaning.
A point consist of a x- and y-value. In technical used sin-functions x is almost always the time t and because of my loop it has a constant delta to the previous and next time-value.

t = a * t
y(t) = b*sin(c*t)

So you could say that a is a constant to change the scaling in x. The constant b is the Peak-to-peak amplitude. The constant cis manipulating the period.

But I am not sure so don’t blame me if this is totally wrong :smiley:
You can also transfer this more usable approach to gdscript. Shouldn’t be that hard.

rolfpancake | 2018-02-06 13:12

This tips for drawing a sine wave helped me a lot. Thanks for this.

Just a quick question.

What is the purpose of a, b and c ?
Are these related to Amplitude and wavelength?
What is the wave equation for which this application is made?

subhnand | 2021-07-15 16:23