-
Notifications
You must be signed in to change notification settings - Fork 3
/
Point.ts
104 lines (91 loc) · 2.47 KB
/
Point.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { Vector } from './Vector';
import { Line } from './Line';
import GlobalConfig from './GlobalConfig';
import { Matrix2x2 } from './Matrix2x2';
/**
* Represents a single point with x, y coordinates.
*/
export class Point {
constructor(public x:number, public y:number) {
}
static fromValues(x: number, y: number) {
return point(x, y);
}
/**
* Returns the vector going from the inputted point p, to this point.
* @param p
*/
minus(p : Point) :Vector {
return new Vector(this.x - p.x, this.y - p.y);
}
/**
* Defines a line by using this point and a vector.
*/
asLine(v: Vector): Line {
return new Line(this, v);
}
/**
* Returns the coordinates of this point as a vector.
*/
asVector(): Vector {
return new Vector(this.x, this.y);
}
/**
* Returns the point reached when starting at this point and then moving according to vector.
* @param v
*/
plus(v: Vector) : Point {
return new Point(this.x + v.x, this.y + v.y);
}
/**
* Returns the distance between this point and p2 squared
* @param p2
*/
distanceSquare(p2: Point): number {
return p2.minus(this).square();
}
/**
* Returns new point that is moved by x, y.
* Same function as plus, but here taking number instead of vector.
* @param x
* @param y
*/
translate(x: number, y: number) {
return new Point(this.x + x, this.y + y);
}
/**
* Rotates this point around a pivotPoint by a certain number of degrees.
* @param pivotPoint
* The point around which this point should rotate
* @param degrees
* The number of degrees that the point should rotate (a circle covers 360 degrees,
* negative values are ok)
*/
rotate(pivotPoint: Point, degrees: number): Point {
const rotationMatrix = Matrix2x2.rotationDegrees(degrees);
const rotated = rotationMatrix.times([this.x, this.y]);
return new Point(rotated[0], rotated[1]);
}
/**
* Returns true if this point and the other have the same coordinates within
* GlobalConfig.precision error.
* @param
* The other point to compare with.
*/
equals(other: Point): boolean {
return Math.abs(this.x - other.x) < GlobalConfig.precision
&& Math.abs(this.y - other.y) < GlobalConfig.precision;
}
/**
* Gives a readable string representing this point.
*/
toString(): string {
return `[${this.x}, ${this.y}]`;
}
}
/**
* Creates a point.
*/
export function point(x: number, y: number): Point {
return new Point(x, y);
}