Oscillating variable

How can i get the value of a variable to oscillate over time using Javascript?

There are two functions which can do this.

If you want the value to oscillate in a smooth curve (like a Sine wave), use Mathf.Sin

If you want the value to oscillate linearly back and forth between two values (like a triangle wave), use Mathf.PingPong

PingPong will return a value between zero and your specified maximum, while Sin will return a value between -1 and 1.

Whichever you choose, you'll want to feed in the value from Time.time, and optionally multiply it up or down depending on how fast you want the value to oscillate. Eg:

// example using PingPong
function Update ()
    // Set the x position to loop between -3 and 3
    transform.position.x = Mathf.PingPong(Time.time, 6) - 3;

// example using Sin
function Update ()
    // Set the x position to loop between -3 and 3
    transform.position.x = Mathf.Sin(Time.time) * 3;

    // Set the y position to loop much faster between -3 and 3
    transform.position.y = Mathf.Sin(Time.time * 5) * 3;

And an example which oscillates the object around its original position (as requested in the comments below):

var originalPosition : Vector3;

function Start ()
    // when the object starts, we record its initial position
    originalPosition = transform.position;

function Update ()
    // when repositioning the object, we add an offset to the original position
    transform.position.x = originalPosition.x + Mathf.Sin(Time.time) * 3;


You may also want to have a look at Mathfx on the Unifycommunity Wiki

This provides:

  • Hermite
  • Sinerp
  • Coserp
  • Berp
  • Bounce
  • SmoothStep
  • NearestPoint
  • NearestPointStrict

Source code is available both in C# and JavaScript - and on the page on the Wiki, you can also find graphs of the different methods.

In case you want to define what the actual values are I think this is the answer

	var startRange : float = 5;	//your chosen start value
		var endRange : float = 24;	//your chose end value
		var oscilationRange = (endRange - startRange)/2;
		var oscilationOffset = oscilationRange + startRange;
		result = oscilationOffset + Mathf.Sin(Time.time) * oscilationRange;

I posted an answer for a different question some how...

Does anyone know how to apply this to rotation? Substituting “rotation” for “position” in the above solution gives weird and useless results.

// do the sinewave
transform.position = pos + axis * Mathf.Sin (Time.time * frequency) * magnitude;
// and rotation
transform.rotation = Quaternion.Euler (0,0,maxrotation +Mathf.Sin (Time.timefrequency)*magnitude);