Page 80 - JavaScript
P. 80
vec.y = Math.sin(dir); // get the y component
If your coordinate system has y as up then you need to switch cos and sin. In this case a positive
direction is in a counterclockwise direction from the x axis.
// get the directional vector where y points up
var dir = 1.4536; // direction in radians
var vec = {};
vec.x = Math.sin(dir); // get the x component
vec.y = Math.cos(dir); // get the y component
Math.hypot
To find the distance between two points we use pythagoras to get the square root of the sum of
the square of the component of the vector between them.
var v1 = {x : 10, y :5};
var v2 = {x : 20, y : 10};
var x = v2.x - v1.x;
var y = v2.y - v1.y;
var distance = Math.sqrt(x * x + y * y); // 11.180339887498949
With ECMAScript 6 came Math.hypot which does the same thing
var v1 = {x : 10, y :5};
var v2 = {x : 20, y : 10};
var x = v2.x - v1.x;
var y = v2.y - v1.y;
var distance = Math.hypot(x,y); // 11.180339887498949
Now you don't have to hold the interim vars to stop the code becoming a mess of variables
var v1 = {x : 10, y :5};
var v2 = {x : 20, y : 10};
var distance = Math.hypot(v2.x - v1.x, v2.y - v1.y); // 11.180339887498949
Math.hypot can take any number of dimensions
// find distance in 3D
var v1 = {x : 10, y : 5, z : 7};
var v2 = {x : 20, y : 10, z : 16};
var dist = Math.hypot(v2.x - v1.x, v2.y - v1.y, v2.z - v1.z); // 14.352700094407325
// find length of 11th dimensional vector
var v = [1,3,2,6,1,7,3,7,5,3,1];
var i = 0;
dist =
Math.hypot(v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++]);
Periodic functions using Math.sin
Math.sin and Math.cos are cyclic with a period of 2*PI radians (360 deg) they output a wave with an
https://riptutorial.com/ 37

