Easier solution still using sin

I found this lesson a little confusing.
After doing a bit more research I found a much easier solution that still uses MathF.Sin that gives a nice smooth oscillating movement. It makes a lot more sense to me.
It uses the Lerp function which returns a number between two numbers…given a percentage.
Unity Vector3.Lerp Function

using UnityEngine;

[DisallowMultipleComponent]
public class MovingObject : MonoBehaviour
{
    [Tooltip("The direction and amount the object must be moved, positive and negative from starting position.")]
    [SerializeField] Vector3 MovementRange;
    [Range(0.1f, 10f)]
    [Tooltip("How fast the object is moving")]
    [SerializeField] float MovementSpeed = 2f;

    private Vector3 startingPosition;

    // Use this for initialization
    void Start()
    {
        startingPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        var movementFactor = Mathf.Sin(Time.time * MovementSpeed);
        movementFactor = movementFactor / 2f + 0.5f; //We need a value between 0 and 1

        transform.position = Vector3.Lerp(startingPosition - MovementRange, startingPosition + MovementRange, movementFactor);
    }
}
1 Like

Ya id imagine they figured the Sin stuff in itself was dense enough of a concept that keeping the functions limited and achieving things with simple math could help demystify whats happening. Though I can see how raw numbers can sometimes feel more abstract than deciphering function behaviors ha :slight_smile:

With your setup there, doing the math to split the amplitude in half and offset it +0.5 only to then lerp -/+ may be redundant (please someone correct me if im wrong, as someone also learning this its a great thought exercise). I think the point of (effectively) remapping the sin to 0-1 was so we had a simple “Start point” and a single “End point (via distance from start)” driven by whats readably 0-100%. Multiplying the single movement value by a raw Sin will return a range in the negative and positive so you should be able to do away with the extra movement factor math and your Lerp for the same result, right? I know some Lerps have “smoothness” multipliers influencing the way the vector is scaled which would be a case for it, or if youre after asymmetrical oscillation :thinking:

Privacy & Terms