I ended up having to assign the ‘period’ variable value in the Start function, otherwise my object never moved. It never moved otherwise even if I set a [Range (>0f, xf)] to the variable and the if (period value is not zero) code. I feel like this is still too cluttered though, maybe some of the code isn’t necessary?
using UnityEngine;
[DisallowMultipleComponent]
public class Oscillator : MonoBehaviour
{
[SerializeField] Vector3 movementVector = new Vector3 (10f, 0f, 0f);
[Range(0.01f, 5f)][SerializeField] float period = 1f;
[SerializeField] float movementFactor;
Vector3 startingPosition;
void Start()
{
startingPosition = transform.position;
period = 1f; //this is how I got my gameObject to move
}
void Update()
{
//set movement factor to pulse automatically - should this go inside the 'if' statement? idk
float cycles = Time.time / period; //grows continually from 0
const float tau = Mathf.PI * 2f;
float rawSinWave = Mathf.Sin(cycles * tau); //goes between -1 and 1
if (period != 0f)
{
movementFactor = rawSinWave / 2f + 0.5f; // 0 - 1 now; (+-1) / 2 = +-0.5; (+-0.5) +0.5 = 0, 1
Vector3 offset = movementVector * movementFactor;
transform.position = startingPosition + offset;
}
}
}