Disclaimer: There's probably an off-the-self way to get this result from Unity with a built in lerp
of some kind. That's a fine idea & it would probably be my first choice. This answer is meant to explain how to get the result manually.
Let's take the expression below apart, understand what it does & doesn't do, and then fix it:
startPosition.x + Mathf.Sin(Time.time * speed)
Starting from the inside & thinking about the math in general, Mathf.Sin(n)
will return a value between -1 & 1 (inclusive).
By using Time.time
instead of n
you get something that will oscillate between -1 & 1 over time.
Multiplying Time.time
by speed
will scale the rate of oscillation. A speed
of 2 will double the rate whereas a speed
of 0.75 will make it one fourth slower.
Adding startPosition.x
will displace the result. For instance, if startPosition.x
has a value of 10.0, then the net result is an oscillation between 9.0 and 11.0.
Thus, the original expression alters the rate and midpoint of the oscillation.
Since you want to oscillate in a region of a particular size, you need to introduce math to scale the range the oscillation. Let's say you want to keep the animation within the bounds of 20 & 25. That requires a range of 5. But recall that sin
goes from -1 to 1, so a scaling factor of 2.5 would change it to -2.5 to 2.5, which is a total range of 5 (part of our goal):
xMin = 20;
xMax = 25;
range = xMax - xMin;
scale = range/2.0;
x = scale * Mathf.Sin(Time.time * speed);
The last step is to move it to the desired location. One way to think about that is to recall that sin
oscillates about a midpoint. If the target region is 20 to 25, then the target midpoint would be 22.5 and if we check the math, 22.5 ± 2.5 gives a result of 20 to 25. Note that the midpoint is actually the same as the starting bound plus half the range, which is the same thing as the scale. So the final expression would be something like this:
xMin = 20;
xMax = 25;
range = xMax - xMin;
scale = range/2.0;
xMid = mMin + scale;
x = xMid + scale * Mathf.Sin(Time.time * speed);
The code above could be simplified, however it has the benefit of being very explicit: you know what each part does making it easier to understand, modify & maintain. Adjust as necessary to fit your needs.