# How does this AND Mathf.Sin actually work?!

Hello there! I’m learning Unity and as a practice exercise after the introduction i wanted to have a SpaceCraft Exposition on my Android device, all is working fine but i really don’t understand how the “levitation” of the ship works!

It’s relatively simple! The idea is to have the ship Oscillate between 2 apparent points and thus giving it a “levitation” feeling.

My old version used the PingPong Function but it didn’t work as intended so i went to the internet for some help and found this cool piece of code:

``````float originalY;

public float floatStrength = 1;

void Start ()
{
this.originalY = this.transform.position.y;
}

void Update ()
{
transform.position = new Vector3(transform.position.x, originalY + ((float)Mathf.Sin(Time.time) * floatStrength), transform.position.z);
}
``````

Now this works amazing! Exactly what i wanted (Reducing the value on the inspector tho!) … but i have absolutely NO idea how the Oscillation works and what is preventing the ship to go higher or lower!

What “Clamps” the ship between the 2 points?!

This honetly blew my mind when it worked xP

Uhm, it’s just sine. I’m not sure what else we could say. The sine function takes an angle (in this case an angle in radians) and returns an oscillating value betwen -1 and 1 for an increasing angle. That’s simply what sine does.

Since you add your sine value to your original y value you move between (y-1) and (y+1) as your original y value is constant.

Mathf.Sin is a function for calculating the sine of an angle.
It takes an angle (in radians) and gives a value between -1 and 1.

Sine is part of trigonometry, high school curriculum, but you don’t really need to know what it is to understand this script.

Just go to the wiki page for sine, Sine and cosine - Wikipedia, and look at the animation for relation to unit circle - this is how your script moves the cube. (That’s a sine wave.)

Look at the animation and imagine time (Time.time) is spinning the circle. Then floatStrength is how large the circle is. It’s the radius of wheel, not the diameter, though.

A floatStrength of 1 means the wheel is 2 units large, and thus would clamp the object so it moves between 1 unit up and 1 unit down, and a floatStrength of 3 would clamp it between 6 units, so 3 up and 3 down.

Thanks alot to @Bunny83 for clarifying a few things!