An easier way to make the sin wave

Hi! Don’t know if anybody has figured this out before (probably have).

I came up with this method to make the smooth sin movement. To me, it seems easier than in the course.

Please take in mind that I’m still quite new to programming.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveBlock : MonoBehaviour
{

[Range(-5, 5)] [SerializeField] float momevent;
Vector3 position = new Vector3(-25.96f, 13.57f, 0f);
float sineInput;
float sinWave;
float timer;
[SerializeField] float movementRange = 5f;
[SerializeField] float movementSpeed;



// Start is called before the first frame update
void Start()
{
    transform.position = position;
    
}

// Update is called once per frame
void Update()
{
    transform.position = position;
    timer = timer + Time.deltaTime + (movementSpeed/100);
    
    if(timer>=2*Mathf.PI)
        timer = 0;
        
    sineInput = timer;
    sinWave = Mathf.Sin(sineInput);
    momevent = sinWave * movementRange;

    position = new Vector3(-25.96f, 13.57f + momevent, 0f);

}

}

Right now it only works on the Y axis.

1 Like

Interesting approach. I’m not sure if I’m right, but a couple of things that you can try to do, and if they work then the code will be a bit cleaner:

  1. do you need the if statement that resets timer to 0? Results from Mathf.Sin(sineInput) should remain within the range between -1 and 1, regardless of how large sineInput is. If you do need timer to be less than 2Mathf.PI*, then the simpler way would be to use the % operator to get the remainder: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#remainder-operator-
  2. Unless I’m misreading your code, sineInput and timer appear to be redundant. Can’t you just use sinWave = Mathf.Sin(timer); and remove all instances of sineInput?

Thank you for your feedback!

As for tip 1, I just don’t want any of my variables to get too large (probably doesn’t matter lol but still I prefer it like this)

As for tip 2, you are 100% correct. I have just modified my code and deleted sineInput, no point in it. I guess I just got lazy and didn’t see that it could be made simpler.

1 Like

That’s a good point, hadn’t considered it. Eliminating the possibility of overflows is always a good practice. I’ll do the same in my code.

limiting the timer to one period is clever. I like that.

Privacy & Terms