-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathc-collision-detector.js
65 lines (55 loc) · 1.46 KB
/
c-collision-detector.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
class CollisionDetector
{
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Setup
constructor(canvas, fieldsize)
{
this.canvas_ = canvas;
this.fieldsize_ = fieldsize;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Methods
collisionAtLocation(location)
{
// Get color
let context = this.canvas_.getContext("2d");
let data = context.getImageData(location[0], location[1], 1, 1).data;
// Check color
if(data[0] == 0 && data[1] == 0 && data[2] == 0)
{
return false;
}
else
{
return true;
}
}
borderAtLocation(location)
{
let collided_with_border = false;
let new_position = [location[0], location[1]]; // Deep copy
// Check if new position is out of bounds (x)
if(location[0] < 0)
{
collided_with_border = true;
new_position[0] = this.fieldsize_[0];
}
else if(location[0] > this.fieldsize_[0])
{
collided_with_border = true;
new_position[0] = 0;
}
// Check if new position is out of bounds (y)
if(location[1] < 0)
{
collided_with_border = true;
new_position[1] = this.fieldsize_[1];
}
else if(location[1] > this.fieldsize_[1])
{
collided_with_border = true;
new_position[1] = 0;
}
return [new_position, collided_with_border];
}
}