Why are we dividing rawSinWave by 2f?

Hey guys,

I’m new to coding and not great at Maths, please be patient with me haha.

I’m referencing this code from the Oscillator script:

myTime += Time.deltaTime;
float cycles = myTime / period;

const float tau = Mathf.PI * 2;
float rawSinWave = Mathf.Sin(cycles + tau);

movementFactor = rawSinWave / 2f + 0.5f
Vector3 offset = movementFactor * movementVector;
transform.position = startingPos + offset;

I’m following up until we hit:

movementFactor = rawSinWave / 2f + 0.5f;

My question is, why at this point do we divide the result of rawSinWave, which to my understanding somewhere between -1 and +1, by 2?

I’ve probably over thought it at this point so I thought best to just ask!

Thanks

Hi,

You are right. The rawSinWave value ranges from -1 and 1. We want a range of 0 to 1. When we devide rawSinWave by 2, we get a range of -0.5 to 0.5. You can probably guess why we add 0.5 to movementFactor.

Since it’s often helpful to visualise curves, you could test this website. Compare these functions:

y = (sin x)
y = (sin x) * 0.5
y = (sin x) * 0.5 + 0.5

Thanks Nina!

Ok, so, I get that we want a range of 0 to 1 - and that when we divide rawSinWave by 2 that we get a range of -0.5 to 0.5…

But why did we divide rawSinWave by 2 in the first place? Is it just another necessary step to reach 0 to 1?

That’s what I can’t seem to get here, sorry!

We want to multiply the value to our offset value: starting position + x * offset.

0 * offset means no offset. The object appears at its starting position.
1 * offset means that the object appears at the target position.

To achieve this, we need a variable ranging between 0 and 1.

If our variable ranged from -1 to 1 and initial position is on the ground, our object would move into the ground when the variable is < 0. Test it in your code to see what happens.

Ben’s algorithm is designed to make his idea work. It’s not how it must be done. You can change it to achieve a different result if you want.

1 Like

Awesome, thanks so much for your patience Nina!

You’re welcome.


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms