Skip to content

Instantly share code, notes, and snippets.

@stonin
Created March 21, 2019 01:54
Show Gist options
  • Save stonin/d9b52b631e8d374a6ca3c5455e41f156 to your computer and use it in GitHub Desktop.
Save stonin/d9b52b631e8d374a6ca3c5455e41f156 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[DisallowMultipleComponent]
public class Oscillator : MonoBehaviour
{
[SerializeField] Vector3 movementVector = new Vector3(0f, -20f, 0f);
[SerializeField] float period = 2f;
[Range (0,1)] [SerializeField]
float movementFactor; // 0 for not moved, 1 for moved completely.
Vector3 startingPos;
// Start is called before the first frame update
void Start()
{
startingPos = transform.position;
}
// Update is called once per frame
void Update()
{
if (period <= Mathf.Epsilon)
{
transform.position = startingPos;
}
else
{
Oscillate();
}
}
private void Oscillate()
{
float cycles = Time.time / period;
const float tau = Mathf.PI * 2f; // just a number, about 6.28
float rawSinWave = Mathf.Sin(cycles * tau); // goes from -1 to +1
movementFactor = rawSinWave / 2f + 0.5f;
Vector3 offset = movementVector * movementFactor;
transform.position = startingPos + offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment