-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRectangle.js
More file actions
73 lines (73 loc) · 1.6 KB
/
Rectangle.js
File metadata and controls
73 lines (73 loc) · 1.6 KB
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
/**
* Represents a rectangle for drawing and collision testing
*/
class Rectangle
{
/**
* X coordinate of the top-left corner
*/
x = 0;
/**
* Y coordinate of the top-left corner
*/
y = 0;
/**
* Rectangle width
*/
width = 1;
/**
* Rectangle height
*/
height = 1;
/**
* Creates a new rectangle given origin corner and dimensions
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
*/
constructor(x,y,w,h)
{
// normalise the rectangle to ensure widht and height are positive
// this is needed for collision tests
if(w<0)
{
w*=-1;
x-=w;
}
if(h<0)
{
h*=-1;
y-=h;
}
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
/**
* Checks if a point is inside the rectangle.
* @param {number} x
* @param {number} y
* @returns true if point inside Rectangle false otherwise
*/
testPoint(x,y)
{
return this.x <= x
&& this.x + this.width > x
&& this.y <= y
&& this.y + this.height > y;
}
/**
* Checks if this rectangle overlaps another rectangle
* @param {Rectangle} rect - the other Rectangle
* @returns true if the Rectangles overlap false otherwise
*/
testRect(rect)
{
return this.x <= rect.x + rect.width
&& this.x + this.width > rect.x
&& this.y <= rect.y + rect.height
&& this.y + this.height > rect.y;
}
}