-
Notifications
You must be signed in to change notification settings - Fork 34
/
point.js
132 lines (129 loc) · 2.97 KB
/
point.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
function Point(x, y) {
switch(arguments.length) {
case 0:
this.x = 0;
this.y = 0;
break;
case 1:
if (x instanceof Object && "x" in x && "y" in x) {
this.x = x.x;
this.y = x.y;
} else if (x instanceof Object && "X" in x && "Y" in x) {
this.x = x.X;
this.y = x.Y;
} else {
game.error("No x or y in %o", x);
}
break;
case 2:
this.x = x;
this.y = y;
break;
default:
game.error("Illegal arguments in point constructor")
}
}
['fromEvent', 'fromPoint'].map(function(method) {
Point[method] = function(arg) {
return new Point()[method](arg);
};
})
Point.prototype = {
x: 0,
y: 0,
equals: function(o) {
//TODO: fixme
var e = 1e-6;
return Math.abs(this.x - o.x) < e && Math.abs(this.y - o.y) < e;
},
ceil: function() {
this.x = Math.ceil(this.x);
this.y = Math.ceil(this.y);
return this;
},
floor: function() {
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
return this;
},
round: function() {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
clone: function() {
return new Point(this.x, this.y);
},
set: function(x, y) {
this.x = x;
this.y = y;
return this;
},
toScreen: function() {
var x = this.x;
this.x = (x - this.y);
this.y = (x + this.y) / 2;
this.round();
return this;
},
toWorld: function() {
var x = this.x;
this.x = (x / 2 + this.y);
this.y = (this.y - x / 2);
return this;
},
fromEvent: function(e) {
this.x = e.pageX;
this.y = e.pageY;
return this;
},
fromPoint: function(point) {
this.x = point.x;
this.y = point.y;
return this;
},
json: function() {
return {x: this.x, y: this.y};
},
toString: function() {
return "(" + this.x + ", " + this.y + ")";
},
sub: function(p) {
this.x -= p.x;
this.y -= p.y;
return this;
},
add: function(p) {
this.x += p.x;
this.y += p.y;
return this;
},
mul: function(p) {
if (p instanceof Point) {
this.x *= p.x;
this.y *= p.y;
} else {
this.x *= p;
this.y *= p;
}
return this;
},
length: function() {
return Math.hypot(this.x, this.y);
},
normalize: function() {
var len = this.length();
this.x /= len;
this.y /= len;
return this;
},
align: function(to) {
if (to.x != 0) {
this.x = to.x * Math.floor((this.x + to.x/2) / to.x);
}
if (to.y != 0) {
this.y = to.x * Math.floor((this.y + to.y/2) / to.y);
}
return this;
}
}