-
Notifications
You must be signed in to change notification settings - Fork 18
/
SKTilemapPathFinding+Extension.swift
274 lines (197 loc) · 11.1 KB
/
SKTilemapPathFinding+Extension.swift
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
SKTilemap
SKTilemapParser.swift
Created by Thomas Linthwaite on 07/04/2016.
GitHub: https://github.com/TomLinthwaite/SKTilemap
Website (Guide): http://tomlinthwaite.com/
Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki
YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw
Twitter: https://twitter.com/Mr_Tomoso
-----------------------------------------------------------------------------------------------------------------------
MIT License
Copyright (c) 2016 Tom Linthwaite
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-----------------------------------------------------------------------------------------------------------------------
*/
import SpriteKit
import GameplayKit
// MARK: SKTilemap PathFinding Extension
extension SKTilemap {
// MARK: Initialization
/** Initializes the path finding graph. Tiles on the layers named that have the collision property are treated as
collidable (walls / non-walkable). Naming all of the collision layers isn't required. If no names are supplied
all layer tiles are checked for the corresponding property. */
func initializeGraph(collisionProperty collisionProperty: String, collisionLayerNames: [String]? = nil, diagonalsAllowed: Bool) -> Bool {
let time = NSDate()
var layers: [SKTilemapLayer] = []
if collisionLayerNames == nil {
layers = Array(getLayers())
} else {
for name in collisionLayerNames! {
guard let layer = getLayer(name: name) else {
print("SKTilemap: Failed to initialize path finding graph. The collision layer (\(name)) could not be found.")
return false
}
layers.append(layer)
}
}
pathFindingGraph = GKGridGraph(fromGridStartingAt: vector2(0, 0), width: Int32(width), height: Int32(height), diagonalsAllowed: diagonalsAllowed)
removedGraphNodes = []
var nodesToRemove: [GKGridGraphNode] = []
for y in 0..<height {
for x in 0..<width {
for layer in layers {
if let tile = layer.tileAtCoord(x, y) where tile.tileData.properties[collisionProperty] != nil {
nodesToRemove.append(pathFindingGraph!.nodeAtGridPosition(vector2(Int32(x), Int32(y)))!)
break
}
}
}
}
pathFindingGraph?.removeNodes(nodesToRemove)
print("SKTilemap: Initialized path finding graph in \(NSDate().timeIntervalSinceDate(time)) seconds. \(nodesToRemove.count) collidable nodes were removed.")
return true
}
/** Initializes the path finding graph. All tiles on the given layer are treated as collidable tiles (walls / non-walkable). */
func initializeGraph(collisionLayerName collisionLayerName: String, diagonalsAllowed: Bool) -> Bool {
let time = NSDate()
guard let layer = getLayer(name: collisionLayerName) else {
print("SKTilemap: Failed to initialize path finding graph. The collision layer (\(collisionLayerName)) could not be found.")
return false
}
pathFindingGraph = GKGridGraph(fromGridStartingAt: vector2(0, 0), width: Int32(width), height: Int32(height), diagonalsAllowed: diagonalsAllowed)
removedGraphNodes = []
var nodesToRemove: [GKGridGraphNode] = []
for y in 0..<height {
for x in 0..<width {
if layer.tileAtCoord(x, y) != nil {
nodesToRemove.append(pathFindingGraph!.nodeAtGridPosition(vector2(Int32(x), Int32(y)))!)
}
}
}
pathFindingGraph?.removeNodes(nodesToRemove)
print("SKTilemap: Initialized path finding graph in \(NSDate().timeIntervalSinceDate(time)) seconds. \(nodesToRemove.count) collidable nodes were removed.")
return true
}
// MARK: Path Finding
/** Find a path from a start grid position to an end grid position. Will return nil if no path can be found.
Optional parameter removes the starting position from the returned graph, which is usually desired. How ever it
can be turned off.
Returns an array of tilemap coordinates representing the path from start to finish. */
func findPathFrom(x x: Int32, y: Int32, toX: Int32, toY: Int32, removeStartPosition: Bool = true) -> [CGPoint]? {
if x == toX && y == toY {
//print("SKTilemap: Failed to find path. Start and End points are the same.")
return nil
}
guard let graph = pathFindingGraph else {
//print("SKTilemap: Failed to find path. Graph not initialized.")
return nil
}
guard let fromNode = graph.nodeAtGridPosition(vector2(x, y)) else {
//print("SKTilemap. Failed to find path. Invalid start position.")
return nil
}
guard let toNode = graph.nodeAtGridPosition(vector2(toX, toY)) else {
//print("SKTilemap. Failed to find path. Invalid end position.")
return nil
}
var path = graph.findPathFromNode(fromNode, toNode: toNode)
if (removeStartPosition && path.count <= 1) || path.count == 0 {
//print("SKTilemap: Failed to find path.")
return nil
}
if removeStartPosition { path.removeFirst() }
return path.map({ CGPoint(x: Int(($0 as! GKGridGraphNode).gridPosition.x), y: Int(($0 as! GKGridGraphNode).gridPosition.y)) })
}
func findPathFrom(position: CGPoint, to: CGPoint, removeStartPosition: Bool = true) -> [CGPoint]? {
return findPathFrom(x: Int32(position.x), y: Int32(position.y), toX: Int32(to.x), toY: Int32(to.y), removeStartPosition: removeStartPosition)
}
func findPathFrom(position: vector_int2, to: vector_int2, removeStartPosition: Bool = true) -> [CGPoint]? {
return findPathFrom(x: position.x, y: position.y, toX: to.x, toY: to.y, removeStartPosition: removeStartPosition)
}
/** Returns the next position excluding starting position on a given path from point A to B. The return value is a tuple
that, as well as return the next position also returns the total distance of the path. */
func nextPositionOnPathFrom(x: Int32, y: Int32, toX: Int32, toY: Int32) -> (x: Int32, y: Int32, distance: Int)? {
if let path = findPathFrom(x: x, y: y, toX: toX, toY: toY, removeStartPosition: true) {
return (Int32(path.first!.x), Int32(path.first!.y), path.count)
}
return nil
}
func nextPositionOnPathFrom(position: CGPoint, to: CGPoint) -> (position: CGPoint, distance: Int)? {
if let result = nextPositionOnPathFrom(Int32(position.x), y: Int32(position.y), toX: Int32(to.x), toY: Int32(to.y)) {
return (CGPoint(x: Int(result.x), y: Int(result.y)), result.distance)
}
return nil
}
func nextPositionOnPathFrom(position: vector_int2, to: vector_int2) -> (position: vector_int2, distance: Int)? {
if let result = nextPositionOnPathFrom(position.x, y: position.y, toX: to.x, toY: to.y) {
return (vector_int2(result.x, result.y), result.distance)
}
return nil
}
/** Removes a node from the graph. This node can no longer be used when finding a path. */
func removeGraphNodeAtPosition(x x: Int32, y: Int32) {
if let node = pathFindingGraph?.nodeAtGridPosition(vector2(x, y)) {
pathFindingGraph?.removeNodes([node])
removedGraphNodes.append(node)
}
}
func removeGraphNodeAtPosition(position: CGPoint) {
removeGraphNodeAtPosition(x: Int32(position.x), y: Int32(position.y))
}
func removeGraphNodeAtGridPosition(position: vector_int2) {
removeGraphNodeAtPosition(x: position.x, y: position.y)
}
/** Re-adds all nodes that were removed from the graph. This resets the graph to the state it was in when it was
first initialized. */
func resetGraph() {
pathFindingGraph?.addNodes(removedGraphNodes)
removedGraphNodes.forEach({ pathFindingGraph?.connectNodeToAdjacentNodes($0) })
removedGraphNodes = []
}
/** Adds a previously removed node to the grid. Does nothing if the grid already has a node at this position.
Nodes that are added to the grid become valid path positions. */
func addGraphNodeAtPosition(x x: Int32, y: Int32) {
guard let graph = pathFindingGraph else { return }
if x < 0 || x >= Int32(graph.gridWidth) || y < 0 || y >= Int32(graph.gridHeight) { return }
if graph.nodeAtGridPosition(vector2(x, y)) != nil { return }
var nodeToAdd: GKGridGraphNode?
for node in removedGraphNodes {
if node.gridPosition.x == x && node.gridPosition.y == y {
nodeToAdd = node
break
}
}
if nodeToAdd == nil { return }
graph.addNodes([nodeToAdd!])
graph.connectNodeToAdjacentNodes(nodeToAdd!)
}
func addGraphNodeAtPosition(position: CGPoint) {
addGraphNodeAtPosition(x: Int32(position.x), y: Int32(position.y))
}
func addGraphNodeAtGridPosition(position: vector_int2) {
return addGraphNodeAtPosition(x: position.x, y: position.y)
}
func adjacentNodesAtGridPosition(position: vector_int2) -> [vector_int2] {
if pathFindingGraph != nil && pathFindingGraph!.nodeAtGridPosition(position) == nil { return [] }
var adjacentNodes: [vector_int2] = []
for connectedNode in pathFindingGraph!.nodeAtGridPosition(position)!.connectedNodes {
adjacentNodes.append((connectedNode as! GKGridGraphNode).gridPosition)
}
return adjacentNodes
}
}