-
Notifications
You must be signed in to change notification settings - Fork 1
/
BuildingNode.swift
90 lines (71 loc) · 3.04 KB
/
BuildingNode.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
//
// BuildingNode.swift
// ExplodingMonkeys
//
// Created by Julian Moorhouse on 03/09/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import SpriteKit
import UIKit
class BuildingNode: SKSpriteNode {
var currentImage: UIImage!
func setup() {
name = "building"
currentImage = drawBuilding(size: size)
texture = SKTexture(image: currentImage)
configurePhysics()
}
func configurePhysics() {
physicsBody = SKPhysicsBody(texture: texture!, size: size)
physicsBody?.isDynamic = false
physicsBody?.categoryBitMask = CollisionTypes.building.rawValue
physicsBody?.contactTestBitMask = CollisionTypes.banana.rawValue
}
func drawBuilding(size: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: size)
let img = renderer.image { ctx in
let rectangle = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let color: UIColor
switch Int.random(in: 0...2) {
case 0:
color = UIColor(hue: 0.502, saturation: 0.98, brightness: 0.67, alpha: 1)
case 1:
color = UIColor(hue: 0.999, saturation: 0.99, brightness: 0.7, alpha: 1)
default:
color = UIColor(hue: 0, saturation: 0, brightness: 0.67, alpha: 1)
}
color.setFill()
ctx.cgContext.addRect(rectangle)
ctx.cgContext.drawPath(using: .fill)
let lightOnColor = UIColor(hue: 0.19, saturation: 0.67, brightness: 0.99, alpha: 1)
let lightOffColor = UIColor(hue: 0, saturation: 0, brightness: 0.34, alpha: 1)
for row in stride(from: 10, to: Int(size.height - 10), by: 40) {
for col in stride(from: 10, to: Int(size.width - 10), by: 40) {
if Bool.random() {
lightOnColor.setFill()
} else {
lightOffColor.setFill()
}
ctx.cgContext.fill(CGRect(x: col, y: row, width: 15, height: 20))
}
}
}
return img
}
func hit(at point: CGPoint) {
// abs make any negative become positive
// where in coregraphics space the banana hit image
let convertedPoint = CGPoint(x: point.x + size.width / 2, y: abs(point.y - (size.height / 2)))
let renderer = UIGraphicsImageRenderer(size: size)
let img = renderer.image { ctx in
currentImage.draw(at: .zero)
// centre on hit point
ctx.cgContext.addEllipse(in: CGRect(x: convertedPoint.x - 32, y: convertedPoint.y - 32, width: 64, height: 64))
ctx.cgContext.setBlendMode(.clear)
ctx.cgContext.drawPath(using: .fill)
}
texture = SKTexture(image: img)
currentImage = img
configurePhysics()
}
}