-
Notifications
You must be signed in to change notification settings - Fork 4
/
world-pos-data.ts
57 lines (50 loc) · 1.49 KB
/
world-pos-data.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
import { Writer } from '../writer';
import { Reader } from '../reader';
import { DataPacket } from '../packet';
import { Point } from '../models/point';
export class WorldPosData implements DataPacket, Point {
x: number;
y: number;
/**
* Creates a new point at the origin or at the provided, x, y.
* @param x An x value for this point. Defaults to 0.
* @param y A y value for this point. Defaults to 0.
*/
constructor(x?: number, y?: number) {
this.x = x || 0;
this.y = y || 0;
}
read(reader: Reader): void {
this.x = reader.readFloat();
this.y = reader.readFloat();
}
write(writer: Writer): void {
writer.writeFloat(this.x);
writer.writeFloat(this.y);
}
/**
* Returns the square distance between this point and the other point.
* @param point The other point.
*/
squareDistanceTo<T extends Point>(point: T): number {
if (!point || typeof point.x !== 'number' || typeof point.y !== 'number') {
throw new TypeError(`Parameter "point" must be a Point, not ${typeof point}`);
}
const a = point.x - this.x;
const b = point.y - this.y;
return a ** 2 + b ** 2;
}
/**
* Returns the distance between this point and the other point.
* @param point The other point.
*/
distanceTo<T extends Point>(point: T): number {
return Math.sqrt(this.squareDistanceTo(point));
}
/**
* Returns a new `Point` which has the same x and y values.
*/
clone(): WorldPosData {
return new WorldPosData(this.x, this.y);
}
}