-
Notifications
You must be signed in to change notification settings - Fork 0
/
Navigation.js
97 lines (79 loc) · 2.32 KB
/
Navigation.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
const NAVIGATION_MODE = {
ROUTE: 1,
DIRECTION: 2
};
class NavigationMark extends MapObject {
constructor(options = {}) {
super(options);
this.color = "#d56fff";
this.char = "*";
}
}
class Navigation extends EventListener {
constructor(game, options = {}) {
super();
const {
mode = NAVIGATION_MODE.ROUTE
} = options;
this.game = game;
this.mode = mode;
this.locating = null;
this.game.on("init", e => {
//If there is an update to the map, update the navigation as well
this.game.map.on("update", e => {
if(!this.game.isRunning) return;
if(this.locating) this.locate(this.locating);
});
});
}
locate(type) {
if(!Utils.subclassOf(type, MapObject)) throw new Error("Type must be a MapObject");
//Find the path to the object
const result = this.game.map.find(this.game.map.getPlayer().position, object => {
if(object instanceof type) return 1;
if(object instanceof Player) return 0;
if(object instanceof Solid) return -1;
return 0;
});
//Clear the previous navigation marks
this.clearMap();
this.dispatchEvent("update", {type, result});
if(result.found) {
//Create the navigation marks
if(this.mode === NAVIGATION_MODE.DIRECTION) {
this.markDirection(result.path);
} else if(this.mode === NAVIGATION_MODE.ROUTE) {
this.highlightRoute(result.path);
}
this.locating = type;
this.dispatchEvent("navigate", {type, result});
return true;
} else {
//No path to the object found
this.locating = null;
this.dispatchEvent("unreachable", {type, result});
return false;
}
}
clearMap() {
this.game.map.objects = this.game.map.objects.filter(object => !(object instanceof NavigationMark));
this.game.renderer.renderFrame();
}
highlightRoute(path) {
//Loop all the path positions and create a NavigationMark for each one
for(const position of path) {
const mark = new NavigationMark({position: position});
this.game.map.objects.push(mark);
}
this.game.renderer.renderFrame();
}
markDirection(path) {
//Pick just the first position in the path and highlight the direction
this.highlightRoute(path.slice(0, 1));
}
toggleOff() {
this.locating = null;
this.clearMap();
this.dispatchEvent("update", {type: null, result: null});
}
}