-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameScene.swift
309 lines (249 loc) · 10.9 KB
/
GameScene.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//
// GameScene.swift
// MarbleMaze
//
// Created by Julian Moorhouse on 18/08/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import CoreMotion
import SpriteKit
enum LetterType: Character {
case wall = "x"
case vortex = "v"
case star = "s"
case finishPoint = "f"
case teleport = "t"
case empty = " "
}
enum CollisionTypes: UInt32 {
case player = 1
case wall = 2
case star = 4
case vortex = 8
case finish = 16
case teleport = 32
}
enum NodeNames: String {
case wall
case vortex
case star
case finish
case teleport
// case empty = " "
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var player: SKSpriteNode!
var lastTouchedPosition: CGPoint?
var motionManager: CMMotionManager?
var isGameOver = false
var currentLevel = 1
var lastTeleport: SKNode!
var scoreLabel: SKLabelNode!
var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.horizontalAlignmentMode = .left
scoreLabel.position = CGPoint(x: 16, y: 16)
scoreLabel.zPosition = 2
addChild(scoreLabel)
score = 0
loadLevel(number: currentLevel)
createPlayer()
physicsWorld.gravity = .zero
physicsWorld.contactDelegate = self
motionManager = CMMotionManager()
motionManager?.startAccelerometerUpdates()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
lastTouchedPosition = location
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
lastTouchedPosition = location
let nodesAtPoint = nodes(at: location) // all nodes under finger
for case let node as SKSpriteNode in nodesAtPoint {
if node.name != NodeNames.teleport.rawValue {
lastTeleport = nil
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchedPosition = nil
}
func didBegin(_ contact: SKPhysicsContact) {
guard let nodeA = contact.bodyA.node else { return }
guard let nodeB = contact.bodyB.node else { return }
if nodeA == player {
playerCollided(with: nodeB)
} else if nodeB == player {
playerCollided(with: nodeA)
}
// https://www.hackingwithswift.com/read/26/4/contacting-but-not-colliding
// 4:26
}
override func update(_ currentTime: TimeInterval) {
guard isGameOver == false else { return }
#if targetEnvironment(simulator)
if let lastTouchedPosition = lastTouchedPosition {
let diff = CGPoint(x: lastTouchedPosition.x - player.position.x, y: lastTouchedPosition.y - player.position.y)
// mimic earths gravity aka / 10
physicsWorld.gravity = CGVector(dx: diff.x / 100, dy: diff.y / 100)
}
#else
if let accelerometerData = motionManager?.accelerometerData {
// x and y swapped as we are in landscape
physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.y * -50, dy: accelerometerData.acceleration.x * 50)
}
#endif
}
func loadNodeWall(_ position: CGPoint) {
let node = SKSpriteNode(imageNamed: "block")
node.name = NodeNames.wall.rawValue
node.position = position
node.physicsBody = SKPhysicsBody(rectangleOf: node.size)
node.physicsBody?.categoryBitMask = CollisionTypes.wall.rawValue
// will not move around with gravity
node.physicsBody?.isDynamic = false
addChild(node)
}
func loadNodeVortex(_ position: CGPoint) {
let node = SKSpriteNode(imageNamed: "vortex")
node.name = NodeNames.vortex.rawValue
node.position = position
// spin forever
node.run(SKAction.repeatForever(SKAction.rotate(byAngle: .pi, duration: 1)))
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody?.isDynamic = false
// it is a vortex for collision purposes
node.physicsBody?.categoryBitMask = CollisionTypes.vortex.rawValue
// we want to be told about collisions
node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
// bounce off nothing
node.physicsBody?.collisionBitMask = 0
addChild(node)
}
func loadNodeObject(_ position: CGPoint, imageName: String, type: CollisionTypes, nodeName: NodeNames) {
let node = SKSpriteNode(imageNamed: imageName)
node.size = CGSize(width: 64, height: 64)
node.name = nodeName.rawValue
node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2)
node.physicsBody?.isDynamic = false
node.physicsBody?.categoryBitMask = type.rawValue
// we want to be told about collisions
node.physicsBody?.contactTestBitMask = CollisionTypes.player.rawValue
// bounce off nothing
node.physicsBody?.collisionBitMask = 0
node.position = position
addChild(node)
}
func loadLevel(number: Int) {
guard let levelURL = Bundle.main.url(forResource: "level\(number)", withExtension: "txt") else {
fatalError("Could not find level1.txt in the app bundle.")
}
guard let levelString = try? String(contentsOf: levelURL) else {
fatalError("Could not find level1.txt in the app bundle.")
}
let lines = levelString.components(separatedBy: "\n")
// reading from bottom to top, because on inverted y access in SpriteKit
for (row, line) in lines.reversed().enumerated() {
for (column, letter) in line.enumerated() {
// 64 is the block size and 32 for the center of the block, as SpriteKit positions items from the center
let position = CGPoint(x: (64 * column) + 32, y: (64 * row) + 32)
if letter == LetterType.wall.rawValue {
loadNodeWall(position)
} else if letter == LetterType.vortex.rawValue {
loadNodeVortex(position)
} else if letter == LetterType.star.rawValue {
loadNodeObject(position, imageName: "star", type: .star, nodeName: .star)
} else if letter == LetterType.finishPoint.rawValue {
loadNodeObject(position, imageName: "finish", type: .finish, nodeName: .finish)
} else if letter == LetterType.teleport.rawValue {
loadNodeObject(position, imageName: "target0", type: .teleport, nodeName: .teleport)
} else if letter == LetterType.empty.rawValue {
// this is an empty space - do nothing
} else {
fatalError("Unknown level letter: '\(letter)'")
}
}
}
}
func createPlayer() {
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 96, y: 672)
player.zPosition = 1
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.allowsRotation = false
player.physicsBody?.linearDamping = 0.5
player.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
// tell us about these
player.physicsBody?.contactTestBitMask = CollisionTypes.star.rawValue | CollisionTypes.vortex.rawValue | CollisionTypes.finish.rawValue
player.physicsBody?.collisionBitMask = CollisionTypes.wall.rawValue
addChild(player)
}
func playerCollided(with node: SKNode) {
if node.name == NodeNames.vortex.rawValue {
// stop player rolling around like a ball so we can suck it into the vortex
player.physicsBody?.isDynamic = false
isGameOver = true
score -= 1
// move ball over vortex
let move = SKAction.move(to: node.position, duration: 0.25)
let scale = SKAction.scale(by: 0.0001, duration: 0.25)
let remove = SKAction.removeFromParent()
let sequence = SKAction.sequence([move, scale, remove])
player.run(sequence) { [weak self] in
self?.createPlayer()
self?.isGameOver = false
}
} else if node.name == NodeNames.star.rawValue {
node.removeFromParent()
score += 1
} else if node.name == NodeNames.teleport.rawValue {
for child in children {
if child.name == NodeNames.teleport.rawValue, node != lastTeleport {
if child.position.x != node.position.x && child.position.y != node.position.y {
lastTeleport = child
player.physicsBody?.isDynamic = false
let move = SKAction.move(to: child.position, duration: 0)
player.run(move)
player.physicsBody?.isDynamic = true
break
}
}
}
} else if node.name == NodeNames.finish.rawValue {
currentLevel += 1
if currentLevel > 3 {
let gameOver = SKSpriteNode(imageNamed: "game-over")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 1
addChild(gameOver)
} else {
// Remove map objects
for child in children {
if child.name == NodeNames.wall.rawValue ||
child.name == NodeNames.vortex.rawValue ||
child.name == NodeNames.star.rawValue ||
child.name == NodeNames.finish.rawValue {
child.removeFromParent()
}
}
player.removeFromParent()
loadLevel(number: currentLevel)
createPlayer()
}
}
}
}