joeb joeb - 1 year ago 78
Javascript Question

What is this wacky math in three.js

I'm in the process of learning three.js and I keep coming across these wacky math formulas everywhere and I can't understand the WHY.

Here's an example.

mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1 );

If someone can explain the logic to me here would probably make a world of difference to me. From what I can understand from this example is we are taking the current mouse x position on the screen, then dividing by the width of the screen, then multiplying by 2, then subtracting 1. Just seems illogical to me.

example 2

geometry.rotateX( - Math.PI / 2 );

Answer Source

First I'm going to assume you've missed the significance of some_distance/total_distance. It is basically the same as saying some_number_on_a_ruler/ruler_length - the result is basically a number between 0 and 1 that represent the location of the first number relative to the second number.

For example, if you do:

(event.clientX / window.innerWidth) * 100

You will get a number, in percent, that represent where the mouse is. So if you do:

(event.clientX / window.innerWidth) * 2

You will get a number between 0 and 2 that represent the mouse position. If instead you do:

(event.clientX / window.innerWidth) * 2 - 1 

You will get a number between -1 and 1 that represent the mouse position where 0 represent the middle of the window. That's what the number mean. The closer it is to 0 the closer it is to the middle of the window.

As for - ( event.clientY / window.innerHeight ) * 2 + 1. That's the same thing, only it's actually a rearrangement of:

- (( event.clientY / window.innerHeight ) * 2 - 1 )

The inner part is exactly the same as for clientX only the sign have been inverted.

Now, for geometry.rotateX( - Math.PI / 2 ) what you need to know is that 2PI is 360 degrees. Forget about degrees COMPLETELY if you want to do a lot of geometry. The natural unit for angles is radians. Indeed it is so natural we normally don't even say 2PI radians in math, we just say 2PI.

If 2PI is one circle, then PI is half a circle so PI/2 is a quarter circle or 90 degrees. So it's rotating by 90 degrees.