import SwiftUI
import SpriteKit
struct ContentView: View {
@ObservedObject var counter = Counter()
var scene: SKScene {
let scene = GameScene()
scene.counter = counter
scene.size = CGSize(width: 300, height: 400)
scene.scaleMode = .fill
return scene
}
var body: some View {
VStack{
SpriteView(scene: scene)
.frame(width: 300, height: 400)
.ignoresSafeArea()
// Button{
// counter.add(count: 1)
// counter.reset()
// } label: {
// Text("reset to count")
// }
Text("New count = \(counter.count)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
/////////////////////////////////
Counter.swift
import SwiftUI
class Counter: ObservableObject {
@Published var count : Int = 0
func add(count: Int) {
self.count += count
// print("Add \(count); new total: \(self.count)")
}
func reset() { count = 0 }
}
//////////////////////////
GameScene.swift
import SwiftUI
import SpriteKit
class GameScene: SKScene {
var counter : Counter?
var count = 0
override func didMove(to view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let box = SKSpriteNode(color: SKColor.red, size: CGSize(width: 50, height: 50))
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
self.addChild(box)
// score += 1
// counter.add(count: 1)
counter?.add(count: 1)
}
}