I'm using SwiftUI and trying to implement touchesBegan method from an SKScene object so that touches on the left half of a SpriteView create a green box, and touches on the right half create a red box. This works to a point, but cannot handle multiple simultaneous touches. It seems to work fine when not run from within a SwiftUI SpriteView (i.e. when presented by an SKView of a UIViewController). Here's my GameScene.swift...
import SwiftUI
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let colour: SKColor
let location = touch.location(in: self)
if location.x > self.frame.midX {
print("right")
colour = .red
}
else {
print("left")
colour = .green
}
let box = SKSpriteNode(color: colour, size: CGSize(width: 50, height: 50))
box.position = location
box.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 50, height: 50))
addChild(box)
}
}
}
...and my ContentView.swift...
import SwiftUI
import SpriteKit
struct ContentView: View {
var scene: SKScene {
let scene = GameScene()
scene.size = CGSize(width: 500, height: 350)
scene.scaleMode = .fill
return scene
}
var body: some View {
SpriteView(scene: scene)
.frame(width: 500, height: 350)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Any ideas?
Solution:
Need to know: