Smooth Object Movement for 2D and 3D Unity Games with this Oscillator Script
Attach the Oscillator.cs to a GameObject you want to Oscillate.
The Move To Vector defines the Movement End Vector Point from Local Position and Rotation.
The Time for Movement defines the amount of time need for the Object to perform a full Movement Cycle in Seconds.
This Script can be really nice in Platformer Games that has Moving Elements. It gives the Level Designer more Options to Design the Level.
This Script find use in 2D and 3D Scenarios, just try it out. The Oscillator can be extendet and adjusted with own needs and Specifications.
Oscillator.cs
using UnityEngine;
///
/// The Oscillator can be used to Transform a GameObject as Sinus between Position A and Position B
/// It Smoothly Translates the Position of an Object
/// Slows Down at the End and Beginning and Speed Up towards Center
/// Can be used in 2D and 3D Games
///
public class Oscillator : MonoBehaviour
{
[SerializeField] float sinModifier = 3f;
float CalculateSin => Mathf.PI * sinModifier;
[SerializeField] Vector3 moveToVector;
[SerializeField] float timeForMovement = 2f;
Vector3 startingPosition;
float movementFactor;
void Start()
{
startingPosition = transform.position;
}
void Update()
{
if (timeForMovement <= Mathf.Epsilon)
return;
float timeCycle = Time.time / timeForMovement;
float rawSinWave = Mathf.Sin(timeCycle * CalculateSin);
movementFactor = (rawSinWave + 1f) / 2f;
Vector3 offset = moveToVector * movementFactor;
transform.position = startingPosition + offset;
}
}