-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameScene.swift
294 lines (237 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
//
// GameScene.swift
// ExplodingMonkeys
//
// Created by Julian Moorhouse on 03/09/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import GameplayKit
import SpriteKit
enum CollisionTypes: UInt32 {
case banana = 1
case building = 2
case player = 4
// case wind = 8
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var buildings = [BuildingNode]()
weak var viewController: GameViewController?
var player1: SKSpriteNode!
var player2: SKSpriteNode!
var banana: SKSpriteNode!
var rainParticles: SKEmitterNode!
var gameOver: SKSpriteNode!
var currentPlayer = 1
var windDirection: Int = -4
var windSpeed: CGFloat = 0.85
override func didMove(to view: SKView) {
backgroundColor = UIColor(hue: 0.669, saturation: 0.99, brightness: 0.67, alpha: 1)
createBuildings()
createPlayers()
rainParticles = SKEmitterNode(fileNamed: "Rain.sks")
rainParticles.position = CGPoint(x: size.width / 2, y: size.height)
rainParticles.name = "rainParticle"
rainParticles.targetNode = scene
rainParticles.particlePositionRange = CGVector(dx: frame.size.width, dy: frame.size.height)
rainParticles.zPosition = -1
rainParticles.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
rainParticles.physicsBody?.affectedByGravity = true
addChild(rainParticles)
gameOver = SKSpriteNode(imageNamed: "game-over")
gameOver.position = CGPoint(x: 512, y: 384)
gameOver.zPosition = 50
increaseDifficulty(delayAmount: 0)
physicsWorld.contactDelegate = self
}
func didBegin(_ contact: SKPhysicsContact) {
let firstBody: SKPhysicsBody
let secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
guard let firstNode = firstBody.node else { return }
guard let secondNode = secondBody.node else { return }
if firstNode.name == "banana", secondNode.name == "building" {
bananaHit(building: secondNode, atPoint: contact.contactPoint)
}
if firstNode.name == "banana", secondNode.name == "player1" {
destroy(player: player1)
}
if firstNode.name == "banana", secondNode.name == "player2" {
destroy(player: player2)
}
}
override func update(_ currentTime: TimeInterval) {
guard banana != nil else { return }
// if off the left or right edge remove banana
if abs(banana.position.y) > 1000 {
banana.removeFromParent()
banana = nil
changePlayer()
}
}
func createBuildings() {
var currentX: CGFloat = -15
while currentX < 1024 {
let size = CGSize(width: Int.random(in: 2...4) * 40, height: Int.random(in: 300...600))
currentX += size.width + 2
let building = BuildingNode(color: .red, size: size)
// from centre
building.position = CGPoint(x: currentX - (size.width / 2), y: size.height / 2)
building.setup()
addChild(building)
buildings.append(building)
}
}
func launch(angle: Int, velocity: Int) {
let speed = Double(velocity) / 10
let radians = deg2rad(degrees: angle)
if banana != nil {
banana.removeFromParent()
banana = nil
}
banana = SKSpriteNode(imageNamed: "banana")
banana.name = "banana"
banana.physicsBody = SKPhysicsBody(circleOfRadius: banana.size.width / 2)
banana.physicsBody?.categoryBitMask = CollisionTypes.banana.rawValue
// can hit buildings or players
banana.physicsBody?.collisionBitMask = CollisionTypes.building.rawValue | CollisionTypes.player.rawValue
// can bounce off them and tell us when it does so
banana.physicsBody?.contactTestBitMask = CollisionTypes.building.rawValue | CollisionTypes.player.rawValue
// very slow / use selectively - small object
banana.physicsBody?.usesPreciseCollisionDetection = true
addChild(banana)
if currentPlayer == 1 {
// arm position of throw monkey
banana.position = CGPoint(x: player1.position.x - 30, y: player1.position.y + 40)
banana.physicsBody?.angularVelocity = -20
let raiseArm = SKAction.setTexture(SKTexture(imageNamed: "player1Throw"))
let lowerArm = SKAction.setTexture(SKTexture(imageNamed: "player"))
let pause = SKAction.wait(forDuration: 0.15)
let sequence = SKAction.sequence([raiseArm, pause, lowerArm])
player1.run(sequence)
// give banana a push to the right
let impulse = CGVector(dx: cos(radians) * speed, dy: sin(radians) * speed)
banana.physicsBody?.applyImpulse(impulse)
} else {
banana.position = CGPoint(x: player2.position.x + 30, y: player2.position.y + 40)
banana.physicsBody?.angularVelocity = 20
let raiseArm = SKAction.setTexture(SKTexture(imageNamed: "player2Throw"))
let lowerArm = SKAction.setTexture(SKTexture(imageNamed: "player"))
let pause = SKAction.wait(forDuration: 0.15)
let sequence = SKAction.sequence([raiseArm, pause, lowerArm])
player2.run(sequence)
// give banana a push to the left
let impulse = CGVector(dx: cos(radians) * -speed, dy: sin(radians) * speed)
banana.physicsBody?.applyImpulse(impulse)
}
}
func createPlayers() {
player1 = SKSpriteNode(imageNamed: "player")
player1.name = "player1"
player1.physicsBody = SKPhysicsBody(circleOfRadius: player1.size.width / 2)
// they are a player
player1.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
// bounce off bananas
player1.physicsBody?.collisionBitMask = CollisionTypes.banana.rawValue
// tell us when you hit bananas
player1.physicsBody?.contactTestBitMask = CollisionTypes.banana.rawValue
// don't let them be moved around by gravity
player1.physicsBody?.isDynamic = false
// not the building that's slightly off the screen
let player1Building = buildings[1]
player1.position = CGPoint(x: player1Building.position.x, y: player1Building.position.y + ((player1Building.size.height + player1.size.height) / 2))
addChild(player1)
player2 = SKSpriteNode(imageNamed: "player")
player2.name = "player2"
player2.physicsBody = SKPhysicsBody(circleOfRadius: player2.size.width / 2)
player2.physicsBody?.categoryBitMask = CollisionTypes.player.rawValue
player2.physicsBody?.collisionBitMask = CollisionTypes.banana.rawValue
player2.physicsBody?.contactTestBitMask = CollisionTypes.banana.rawValue
player2.physicsBody?.isDynamic = false
let player2Building = buildings[buildings.count - 2]
player2.position = CGPoint(x: player2Building.position.x, y: player2Building.position.y + ((player2Building.size.height + player2.size.height) / 2))
addChild(player2)
}
func deg2rad(degrees: Int) -> Double {
// degrees to radians
return Double(degrees) * .pi / 180
}
func bananaHit(building: SKNode, atPoint contactPoint: CGPoint) {
guard let building = building as? BuildingNode else { return }
// where on the building was hit
let buildingLocation = convert(contactPoint, to: building)
building.hit(at: buildingLocation)
if let explosion = SKEmitterNode(fileNamed: "hitBuilding") {
explosion.position = contactPoint
addChild(explosion)
}
// fix for small bug if banana hits two building at the same time, which would explode twice and would call change player twice. Node will instantly no longer be a banana with name cleared
banana.name = ""
banana.removeFromParent()
banana = nil
if currentPlayer == 1 {
viewController?.score.p1 += 10
} else {
viewController?.score.p2 += 10
}
changePlayer()
}
func destroy(player: SKSpriteNode) {
if let explosion = SKEmitterNode(fileNamed: "hitPlayer") {
explosion.position = player.position
addChild(explosion)
}
player.removeFromParent()
banana.removeFromParent()
if (self.viewController?.gameRound ?? 0) >= 3 {
self.viewController?.launchButton.isEnabled = false
self.viewController?.velocitySlider.isEnabled = false
self.viewController?.angleSlider.isEnabled = false
addChild(gameOver)
} else {
self.viewController?.gameRound += 1
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let newGame = GameScene(size: self.size)
newGame.viewController = self.viewController
self.viewController?.currentGame = newGame
if self.currentPlayer == 1 {
self.viewController?.score.p1 += 100
} else {
self.viewController?.score.p2 += 100
}
self.changePlayer()
newGame.currentPlayer = self.currentPlayer
let transition = SKTransition.doorway(withDuration: 1.5)
self.view?.presentScene(newGame, transition: transition)
}
increaseDifficulty(delayAmount: 2)
}
}
func changePlayer() {
if currentPlayer == 1 {
currentPlayer = 2
} else {
currentPlayer = 1
}
viewController?.activatePlayer(number: currentPlayer)
}
func increaseDifficulty(delayAmount: Double) {
if viewController?.wind.direction != nil {
windDirection = Int.random(in: -1...4)
windSpeed += 0.5
}
DispatchQueue.main.asyncAfter(deadline: .now() + delayAmount) {
self.viewController?.wind.direction = self.windDirection
self.viewController?.wind.speed = self.windSpeed
}
physicsWorld.gravity = CGVector(dx: windDirection, dy: -8)
physicsWorld.speed = windSpeed
rainParticles.xAcceleration = physicsWorld.gravity.dx * 20
rainParticles.yAcceleration = physicsWorld.gravity.dy * 5
}
}