【发布时间】:2020-08-01 17:13:59
【问题描述】:
我正在开发一个简单的游戏,以在 Xcode 12 中使用 SpriteKit 学习 SwiftUI 的新功能。当用户触摸 SKScene touchesBegan() 时,一切都按预期工作。当用户触摸 Circle() gesture(DragGesture()) 时,我调用了相同的函数,但没有显示任何内容。我可以从日志中得知函数 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]))
}
}
}
【问题讨论】:
标签: ios sprite-kit swiftui skscene ios14