the official Apple documentation here is a bit misleading. WKInterfaceSKScene is not needed, you can simple use SprikeKit for this. I was able to get a cyan ball to fall and bounce mid screen on the watch by modifying the Pong example from the watchOS with SwiftUI book. You can setup the same starter project for yourself by following the below steps:
Start a watchOS App in XCode.
Create a new swift file (which will be your game scene and put the code shown below in it).
Modify the ContentView file by importing SpriteKit and SwiftUI and by modifying the body variable in the ContentView struct to look like the below.
Build your project and it should show a cyan ball that falls and bounces mid screen.
var body: some View {
GeometryReader { reader in
SpriteView(scene: GameScene(size: reader.size))
.focusable()
}
}
import SpriteKit
import SwiftUI
final class GameScene: SKScene {
private let cyan = UIColor(red: 0.0, green: 1.0, blue: 1.0, alpha: 1.0)
private var ball: SKShapeNode!
override init(size: CGSize) {
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
// This was created via autofix
fatalError("This should never be called")
}
override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
}
}
extension GameScene {
override func sceneDidLoad() {
super.sceneDidLoad()
ball = createBall()
addChild(ball)
let border = SKPhysicsBody(edgeLoopFrom: frame)
border.friction = 0
border.restitution = 1
physicsBody = border
physicsWorld.contactDelegate = self
}
func createBall() -> SKShapeNode {
let node = SKShapeNode(circleOfRadius: 15)
node.position = .init(x: frame.midX, y: frame.midY)
node.fillColor = cyan
let body = SKPhysicsBody(circleOfRadius: 5)
body.linearDamping = 0
body.angularDamping = 0
body.restitution = 1.0
node.physicsBody = body
return node
}
}
extension GameScene: SKPhysicsContactDelegate {
func didEnd(_ contact: SKPhysicsContact) {
ball.physicsBody?.velocity = .zero
ball.physicsBody?.applyImpulse(.init())
}
}
extension SKPhysicsBody {
func category(_ category: ShapeType, collidesWith: ShapeType, isDynamic: Bool = true) {
categoryBitMask = category.rawValue
collisionBitMask = collidesWith.rawValue
contactTestBitMask = collidesWith.rawValue
fieldBitMask = 0
allowsRotation = false
affectedByGravity = false
friction = 0
restitution = 0
self.isDynamic = isDynamic
}
}
struct ShapeType: OptionSet {
let rawValue: UInt32
static let ball = ShapeType(rawValue: 1 << 0)
}