How can i make a sine wave move?

Godot Version

v4.3.stable.mono.official [77dcf97d8]

Question

im trying to make a sine wave kinda like on oscilloscopes or spectrum analizer [here is a animation i found for reference](https://youtu.be/70kBeurvp_Q?si=8pNFXixRI2Js_Zqt) here is the code i have for now:

using Godot;
using System.Drawing;
using System.Linq;

public partial class SineWave : Line2D
{
    private HSlider Freq;
    private float Offset;
    private int intPoints = 20000;
    private int amplitude = 50;
    private Vector2 PrevPoint;
    public override void _Ready()
    {
        Freq = GetNode<HSlider>("FreqSlider");
    }
    public override void _Process(double delta)
    {
        Offset = (float)delta;
        QueueRedraw();
    }

    public override void _Draw()
    {
        var step = 2 * 1 / Freq.Value;
        PrevPoint = new Vector2(0, amplitude * Mathf.Sin(0));
        foreach (int i in Enumerable.Range(1, intPoints))
        {
            var x = i * step;
            var y = amplitude * Mathf.Sin(x * Freq.Value / 100);
            var current_point = new Vector2((float)x, (float)y);
            DrawLine(PrevPoint, current_point, new Godot.Color(1, 1, 1), 2, true);
            PrevPoint = current_point;
        }
    }
}

If you picture it on a graph, moving it left or right along the x axis animates it in (I think) the way you want. The y value is a function of x, so make it a function of (x + some offset) instead, and then change the value of offset over time. It looks like this may have been your plan anyway when you added the Offset variable (it appears unused in the code right now)? You just need to use it when calculating your y value:

var y = amplitude * Mathf.Sin((x + Offset) * Freq.Value / 100);

i tried that but it simply does nothing i found somewhat a solution on the discord server which was incorporating the offset to the prevpoint var like this

        var PrevPoint = new Vector2(0, amplitude * Mathf.Sin(Offset));

but it just moves the first point

ok nvm i found a solution for anyone wondering the code works just change the
offset = delta to offset += delta
and change the y variable inside the foreach to

            var y = amplitude * Mathf.Sin(x * Freq.Value / 100 + Offset);

1 Like