我正在尝试使用 SpriteView() 渲染我的 SKScene 文件。它不显示场景,而只显示空的灰色背景。我用两个不同的 SKScene 文件尝试了这个,它们都被渲染为灰色背景。
但是,如果我完全在代码中定义和初始化一个新的 SKScene(即不使用 SKScene 文件和可视化编辑器),并使用 SpriteView() 渲染它,它工作正常。
我做错了什么?
这里是我的测试代码的例子:
这是渲染SKScene文件的代码。结果:灰色屏幕。注意 GameScene 是一个 SKScene 文件,带有随附的 swift 文件。
import SwiftUI
import SpriteKit
var scene: SKScene {
let scene = GameScene()
scene.scaleMode = .aspectFill
return scene
}
struct ContentView: View {
var body: some View {
SpriteView(scene: scene)
.ignoresSafeArea()
}
}
// to view canvas
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
完全在代码中创建 SKScene 的代码。结果:正确显示场景,交互有效。
import SwiftUI
import SpriteKit
class CodeScene: SKScene {
override func didMove(to view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let box = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
addChild(box)
}
}
// A sample SwiftUI creating a GameScene and sizing it
// at 300x400 points
struct ContentView: View {
var scene: SKScene {
let scene = CodeScene()
scene.size = CGSize(width: 300, height: 400)
scene.scaleMode = .fill
return scene
}
var body: some View {
SpriteView(scene: scene)
.frame(width: 300, height: 400)
.ignoresSafeArea()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
编辑:添加游戏场景 swift 文件:
import SpriteKit
class GameScene: SKScene {
private var Player: SKSpriteNode!
override func didMove(to view: SKView) {
Player = childNode(withName: "//Player") as? SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let touchLocation = touch.location(in: self)
let distance = sqrt(pow(touchLocation.x - Player.position.x, 2) + pow(touchLocation.y - Player.position.y, 2))
let speed: CGFloat = 120.0 // adjust as needed
let duration = TimeInterval(distance / speed)
let moveAction = SKAction.move(to: touchLocation, duration: duration)
Player.run(moveAction)
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}