[英]ios14 Xcode 12 - Sprites do not show when touching SwiftUI objects but work when touching SKScene
我正在开发一个简单的游戏来学习 SwiftUI 和 SpriteKit 在 Xcode 12 中的新功能。当用户触摸 SKScene touchesBegan()
时,一切都按预期工作。 当用户触摸 Circle() gesture(DragGesture())
时,我调用相同的 function,但没有显示。 我可以从日志中看出 function showFragments(location:)
正在被调用,但屏幕上没有显示任何内容。 有任何想法吗?
这是代码:
import SpriteKit
import SwiftUI
struct ContentView: View {
var scene: GameScene {
let scene = GameScene()
scene.size = CGSize(width: 350, height: 600)
scene.scaleMode = .fill
scene.backgroundColor = .white
return scene
}
var body: some View {
ZStack {
SpriteView(scene: scene)
.frame(width: 350, height: 600)
.edgesIgnoringSafeArea(.all)
Circle()
.fill(Color.blue)
.frame(width: 50, height: 50)
.gesture(
DragGesture(minimumDistance: 0.0)
.onChanged({ _ in
self.scene.showFragments(location: CGPoint(x: 150, y: 300))
})
)
}
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.showFragments(location: CGPoint(x: 150, y: 300))
}
public func showFragments(location: CGPoint) {
var i: Int = 0
while i <= 3 {
i += 1
let fragment = SKSpriteNode(texture: SKTexture(imageNamed: "Brown Armor Fragment"))
fragment.position = location
print ("fragment \(i): \(fragment.position)")
let wait = SKAction.wait(forDuration: 1)
let remove = SKAction.run({() in fragment.removeFromParent() })
fragment.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Brown Armor Fragment"), alphaThreshold: 0.1, size: CGSize(width: 8, height: 6.5))
self.addChild(fragment)
let vx = Double.random(in: -1...1)
fragment.physicsBody?.applyImpulse(CGVector(dx: vx, dy: 0))
fragment.run(SKAction.sequence([wait, remove]))
}
}
}
您为场景定义了可计算属性,因此它为圆形手势创建了不同的场景。
解决方案是使用一次定义的场景(使用 Xcode 12 / iOS 14 测试)。 对场景使用以下表达式:
struct ContentView: View {
let scene: GameScene = {
let scene = GameScene()
scene.size = CGSize(width: 350, height: 600)
scene.scaleMode = .fill
scene.backgroundColor = .white
return scene
}()
// ... other code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.