Page 79 - JavaScript
P. 79
console.log(Math.ceil(-5.1)); // -6
console.log(Math.ceil(-5.9)); // -6
Math.atan2 to find direction
If you are working with vectors or lines you will at some stage want to get the direction of a vector,
or line. Or the direction from a point to another point.
Math.atan(yComponent, xComponent) return the angle in radius within the range of -Math.PI to Math.PI
(-180 to 180 deg)
Direction of a vector
var vec = {x : 4, y : 3};
var dir = Math.atan2(vec.y, vec.x); // 0.6435011087932844
Direction of a line
var line = {
p1 : { x : 100, y : 128},
p2 : { x : 320, y : 256}
}
// get the direction from p1 to p2
var dir = Math.atan2(line.p2.y - line.p1.y, line.p2.x - line.p1.x); // 0.5269432271894297
Direction from a point to another point
var point1 = { x: 123, y : 294};
var point2 = { x: 354, y : 284};
// get the direction from point1 to point2
var dir = Math.atan2(point2.y - point1.y, point2.x - point1.x); // -0.04326303140726714
Sin & Cos to create a vector given direction & distance
If you have a vector in polar form (direction & distance) you will want to convert it to a cartesian
vector with a x and y component. For referance the screen coordinate system has directions as 0
deg points from left to right, 90 (PI/2) point down the screen, and so on in a clock wise direction.
var dir = 1.4536; // direction in radians
var dist = 200; // distance
var vec = {};
vec.x = Math.cos(dir) * dist; // get the x component
vec.y = Math.sin(dir) * dist; // get the y component
You can also ignore the distance to create a normalised (1 unit long) vector in the direction of dir
var dir = 1.4536; // direction in radians
var vec = {};
vec.x = Math.cos(dir); // get the x component
https://riptutorial.com/ 36

