Skip to content

Vector class

Rohit Vighne edited this page Aug 22, 2016 · 3 revisions

TorchRay makes heavy use of vector math (as opposed to working directly with angles). The Vector class is used any time an (x, y) or (dx, dy) pair is needed.

Constructor

let vec = new Vector(Number x, Number y)

Returns a new Vector object with the given x and y values.

Properties

x

vec.x -> Number

The horizontal component of the vector (a.k.a. the "run"). May be modified directly.

y

vec.y -> Number

The vertical component of the vector (a.k.a. the "rise"). May be modified directly.

Methods

The following methods can be chained: add, sub, mul, rotate.

add

vec.add(Vector other) -> Vector

Adds the x and y components of other to those of vec. Returns a reference to the modified vec.

sub

vec.sub(Vector other) -> Vector

Subtracts the x and y components of other from those of vec. Returns a reference to the modified vec.

mul

vec.mul(Number factor) -> Vector

Multiplies the x and y components of vec by factor. Returns a reference to the modified vec.

rotate

vec.rotate(Number angle) -> Vector

Rotates vec by angle radians about the origin (0, 0). Returns a reference to the modified vec.

compare

vec.compare(Vector other) -> Number

Returns a number that is positive if vec is longer than other; negative if vec is shorter than other; and zero if vec and length have the exact same magnitude (length). Note: this is not simply the difference between the magnitudes of the two vectors! See the length method below.

length

vec.length() -> Number

Returns the magnitude of the vector (e.g. the distance from (0, 0) to (x, y) using the Pythagorean Distance Formula).

copy

vec.copy() -> Vector

Returns a new Vector that has the same x and y properties as vec. This is important because Vectors are mutable (i.e. performing actions like add() and mul() will modify the vector). If you only want the result of an operation and not its side-effects, you must copy it first and work on the copy.

Clone this wiki locally