GameScene
import SpriteKit
import GameplayKit
import SwiftUI
class GameScene: SKScene, SKPhysicsContactDelegate, ObservableObject {
@Published var gameScore = 0
override func didMove(to view: SKView) {
backgroundColor = .yellow
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
ball()
// addScore()
}
func ball() {
let ball = SKShapeNode(circleOfRadius: 50)
ball.position = CGPoint(x: 100, y: 100)
ball.fillColor = .blue
self.addChild(ball)
}
let removeLabel = SKAction.sequence([SKAction.fadeIn(withDuration: 0.3),
SKAction.wait(forDuration: 0.8), SKAction.fadeOut(withDuration: 0.3)])
override func sceneDidLoad() {
super.sceneDidLoad()
}
func addScore(){
if gameScore < 10 {
gameScore += 2
} else {
gameScore += 4
}
}
}
/////////////
GameScene2
import SpriteKit
import GameplayKit
class GameScene2: SKScene {
override func didMove(to view: SKView) {
backgroundColor = .blue
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: 40, height: 40))
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 40, height: 40))
addChild(box)
}
}
/////////////////////
ContentView
import SwiftUI
import SpriteKit
struct ContentView: View {
@State var switcher = false
@StateObject var gameScene: GameScene = GameScene() // <<: Here 3
var scene: SKScene {
let scene = GameScene()
scene.size = CGSize(width: 216, height: 216)
scene.scaleMode = .fill
// scene.backgroundColor = .yellow
return scene
}
var scene2: SKScene {
let scene2 = GameScene2()
scene2.size = CGSize(width: 216, height: 216)
scene2.scaleMode = .fill
return scene2
}
var body: some View {
// Text("Score: \(gameScene.gameScore)") // <<: Here 4
// .onTapGesture {
// gameScene.addScore() // <<: Here 5
// }
Button(action: {
gameScene.addScore()
}, label: {
Text("Score: \(gameScene.gameScore)")
})
if switcher {
SpriteView(scene: scene)
.frame(width: 256, height: 256)
.ignoresSafeArea()
.background(Color.red)
.onAppear {
scene2.isPaused = true
}
.onDisappear {
scene2.isPaused = false
}
} else {
SpriteView(scene: scene2)
.frame(width: 256, height: 256)
.ignoresSafeArea()
.background(Color.blue)
.onAppear {
scene.isPaused = true
}
.onDisappear {
scene.isPaused = false
}
}
Button {
withAnimation(.easeInOut(duration: 1.0)) {
switcher.toggle()
}
} label: {
Text("SceneMove")
}
}
}