The monorepo from
Add Google AdMob Ads to iOS Apps in a Swift Monorepo
holds three iOS apps built from shared packages, and the newest one, Catcher,
is a 2D game. RealityKit is Apple’s framework for 3D: it draws a scene of
3D objects lit by virtual lights and seen through a virtual camera, moves them
with a physics engine, and reports when they collide. It ships with iOS and
Xcode, and SwiftUI shows a RealityKit scene through a view called
RealityView. Apple now recommends it over SceneKit, its older 3D framework,
deprecated in 2025.
This article adds Bowler to the monorepo: ten-pin bowling on one lane.
You tap the ball to roll it straight, or drag it sideways and flick it up the
screen to roll it from there, and the physics engine knocks the pins over.
A small piece of code you write runs on every redraw of the screen and
marks each pin that has fallen, and the game scores the frames by the real
rules, strikes and spares included. You finish by bowling a game on the
simulator. Every object in the scene is generated in code (no 3D models and
no Reality Composer Pro, Apple’s app for assembling 3D scenes), so the whole app builds from the command line. The
scoring lives in a new BowlingKit package with Swift Testing tests that run
on the Mac without a scene, the best score comes from CoreKit, and the
row of numbers across the top of the screen (frame, score, best) uses a new
view in DesignSystem. make test covers the new app
and package, and make release APP=Bowler tags it Bowler/v1.0.0.
What you end up with
Packages/BowlingKit, the rules of ten-pin bowling (frames, pins standing, score) and their tests.StatLabelinDesignSystem, a number with a caption, for a game’s score line.Apps/Bowler, an iOS app whose RealityKit scene is shown byRealityView: a lane, ten pins and a ball built from generated shapes, with physics, lights, a camera, tap and drag gestures on the ball, and a custom component and system (your own data on each pin, and code that runs on every redraw; Step 7) that find fallen pins.- Bowler in the
Makefile, with its own version, display name, icon, shared scheme and first release tag.
Prerequisites
- The finished
my-appsfolder from Add Google AdMob Ads to iOS Apps in a Swift Monorepo, with its Git history, theShopping/v1.2.0andCatcher/v1.1.0tags, and theTodoList-iPhonesimulator. - Xcode 27 or later on a Mac with Apple silicon. Validated on Xcode 27.1 (build 27A9275) with Swift 6.4 and the iOS 27.0 simulator, on macOS 27.0.1. RealityKit draws on the simulator using the Mac’s GPU, so no iPhone is needed.
- No RealityKit or 3D experience; each part is explained where it is used.
The Swift assumes you have followed the series, including
@Stateand@Observablefrom Build Your First SwiftUI App on macOS, and the per-app setup from Build a 2D Game with SpriteKit in a Swift Monorepo, which Steps 3 to 5 repeat for a fourth app. - No bowling knowledge; Step 1 explains the scoring rules.
- No Apple Developer account.
- Steps 3, 4 and 5 are partly done in Xcode; a command after each part checks the result.
Run every command from inside my-apps.
Step 1: Write the rules of bowling in a package
The scoring is the part of the game easiest to get wrong, and the part
that needs no 3D at all, so it goes in a package of its own, as Catcher’s
rules did in CatcherKit. The rules are those of ten-pin bowling:
- A game is ten frames. In each frame you get up to two rolls (throws of the ball) at ten pins.
- A frame scores the pins knocked down in it, plus a bonus. A strike is all ten pins with the first roll: it ends the frame and scores 10 plus the pins from your next two rolls. A spare is all ten pins with two rolls: it scores 10 plus the pins from your next roll.
- The tenth frame has no next frame to take a bonus from, so a strike or a spare there earns extra rolls (two after a strike, one after a spare), with the pins set up again after each strike or spare. A game of twelve strikes scores the maximum, 300.
Graphics code also calls each redraw of the screen a frame; this article calls those redraws, so frame always means a bowling frame. Create the package and delete the two template files:
mkdir Packages/BowlingKit
cd Packages/BowlingKit
swift package init --type library
cd ../..
rm Packages/BowlingKit/Sources/BowlingKit/BowlingKit.swift Packages/BowlingKit/Tests/BowlingKitTests/BowlingKitTests.swift
Create the file
touch Packages/BowlingKit/Package.swift
The file exists already. Replace its contents with the listing below.
Add the code: Packages/BowlingKit/Package.swift
// swift-tools-version: 6.4
import PackageDescription
let package = Package(
name: "BowlingKit",
platforms: [
.iOS(.v17),
.macOS(.v14),
],
products: [
.library(name: "BowlingKit", targets: ["BowlingKit"]),
],
targets: [
.target(
name: "BowlingKit",
swiftSettings: [
.enableUpcomingFeature("ApproachableConcurrency"),
]
),
.testTarget(
name: "BowlingKitTests",
dependencies: ["BowlingKit"],
swiftSettings: [
.enableUpcomingFeature("ApproachableConcurrency"),
]
),
]
)
Detailed breakdown
- The manifest is
CatcherKit’s with the name changed.BowlingKitdepends on no other package and imports no RealityKit: nothing in it draws.
Create the file
touch Packages/BowlingKit/Sources/BowlingKit/BowlingGame.swift
Add the code: Packages/BowlingKit/Sources/BowlingKit/BowlingGame.swift
/// The rules of ten-pin bowling, kept apart from RealityKit so they can be
/// tested without a scene: which frame it is, how many pins are standing,
/// and the score.
public struct BowlingGame: Equatable, Sendable {
public static let pinCount = 10
public static let frameCount = 10
/// The pins each roll knocked down, one array per frame. The last frame
/// may be unfinished.
public private(set) var frames: [[Int]] = [[]]
/// The pins standing for the next roll. When it goes back to 10, the
/// pins are set up again.
public private(set) var pinsStanding = BowlingGame.pinCount
public init() {}
/// The frame being played, from 1 to 10.
public var frameNumber: Int { frames.count }
public var isOver: Bool {
frames.count == Self.frameCount && Self.isFinished(frames[frames.count - 1], last: true)
}
/// Records a roll that knocked down `pins` of the pins standing.
public mutating func roll(_ pins: Int) {
guard !isOver else { return }
precondition((0...pinsStanding).contains(pins), "Only \(pinsStanding) pins are standing")
frames[frames.count - 1].append(pins)
pinsStanding -= pins
if pinsStanding == 0 {
// A strike or a spare. In the last frame it earns more rolls at a full set.
pinsStanding = Self.pinCount
}
let isLast = frames.count == Self.frameCount
if !isLast, Self.isFinished(frames[frames.count - 1], last: false) {
frames.append([])
pinsStanding = Self.pinCount
}
}
/// The score so far. A strike counts the next two rolls and a spare the
/// next one, as far as they have been rolled.
public var score: Int {
let rolls = frames.flatMap { $0 }
func pins(_ index: Int) -> Int { index < rolls.count ? rolls[index] : 0 }
var total = 0
var index = 0
for _ in 0..<Self.frameCount where index < rolls.count {
if pins(index) == Self.pinCount {
total += Self.pinCount + pins(index + 1) + pins(index + 2)
index += 1
} else if pins(index) + pins(index + 1) == Self.pinCount {
total += Self.pinCount + pins(index + 2)
index += 2
} else {
total += pins(index) + pins(index + 1)
index += 2
}
}
return total
}
/// Frames 1 to 9 end after a strike or two rolls. The last frame ends
/// after two rolls that leave pins standing, or after three.
private static func isFinished(_ frame: [Int], last: Bool) -> Bool {
if last {
return frame.count == 3 || (frame.count == 2 && frame[0] + frame[1] < pinCount)
}
return frame.first == pinCount || frame.count == 2
}
}
Detailed breakdown
- The game stores the rolls, grouped by frame.
framesstarts as one empty frame, androll(_:)appends to the last one. A frame from 1 to 9 ends after a strike or two rolls (isFinished), androll(_:)then opens the next. The tenth frame is never followed by another; it ends after two rolls that leave pins standing, or after three. pinsStandingtells the app what to do with the pins. It drops by the pins knocked down and goes back to 10 whenever none are left standing or a new frame starts. That is the one signal the app needs: when it reads 10, set up a full set of pins; otherwise, clear away the fallen ones and leave the rest. In the tenth frame the same rule sets the pins up again after a strike or spare.roll(_:)checks its input withprecondition. Knocking down more pins than are standing is a bug in the caller, so it stops the program with a message instead of producing a wrong score. A roll after the game is over is ignored, as inCatcherGame.scoreis worked out from the rolls each time it is read. It walks through the rolls frame by frame: a strike counts the next two rolls, a spare the next one, any other frame its own pins. A bonus roll not yet bowled counts as 0, so the score shown during a game is the score so far. Storing a running total would mean going back to fix earlier frames when a bonus arrives.
Create the file
touch Packages/BowlingKit/Tests/BowlingKitTests/BowlingGameTests.swift
Add the code: Packages/BowlingKit/Tests/BowlingKitTests/BowlingGameTests.swift
import Testing
import BowlingKit
struct BowlingGameTests {
private func game(rolling rolls: [Int]) -> BowlingGame {
var game = BowlingGame()
for pins in rolls { game.roll(pins) }
return game
}
@Test(arguments: [
([Int](repeating: 0, count: 20), 0),
([Int](repeating: 1, count: 20), 20),
([5, 5, 3], 16),
([10, 3, 4], 24),
([Int](repeating: 5, count: 21), 150),
([Int](repeating: 10, count: 12), 300),
])
func scores(rolls: [Int], expected: Int) {
#expect(game(rolling: rolls).score == expected)
}
@Test func aFrameEndsAfterTwoRollsOrAStrike() {
var game = BowlingGame()
game.roll(7)
#expect(game.frameNumber == 1)
#expect(game.pinsStanding == 3)
game.roll(2)
#expect(game.frameNumber == 2)
#expect(game.pinsStanding == 10)
game.roll(10)
#expect(game.frameNumber == 3)
#expect(game.pinsStanding == 10)
}
@Test func aSpareInTheLastFrameEarnsOneMoreRoll() {
var game = game(rolling: [Int](repeating: 0, count: 18) + [7, 3])
#expect(!game.isOver)
#expect(game.pinsStanding == 10)
game.roll(5)
#expect(game.isOver)
#expect(game.score == 15)
}
@Test func nothingCountsAfterTheGameIsOver() {
var game = game(rolling: [Int](repeating: 1, count: 20))
#expect(game.isOver)
game.roll(1)
#expect(game.score == 20)
#expect(game.frames.count == BowlingGame.frameCount)
}
}
Detailed breakdown
- The
scorestest runs six games through one function. Witharguments:, Swift Testing runs the test once per pair of rolls and expected score, and reports each case separately. The cases use games you can count by hand: twenty rolls of 0 score 0, twenty 1s score 20,5, 5, 3is a spare worth 13 plus 3 in the next frame (16),10, 3, 4is a strike worth 17 plus 7 (24), twenty-one 5s are ten spares of 15 (150), and twelve strikes are 300.
Run the tests:
SWT_SF_SYMBOLS_ENABLED=0 swift test --package-path Packages/BowlingKit 2>&1 | tail -1
✔ Test run with 4 tests in 1 suite passed after 0.001 seconds.
Four tests: the six scores cases count as one.
Step 2: Add a score label to DesignSystem
Bowler shows three numbers across the top of the screen: the frame, the
score and the best score. A caption over a number is not specific to bowling,
so the view goes into the shared DesignSystem package, where Catcher could
later use it too. The package already sets the look of TodoList and Shopping
with CheckRow.
Create the file
touch Packages/DesignSystem/Sources/DesignSystem/StatLabel.swift
Add the code: Packages/DesignSystem/Sources/DesignSystem/StatLabel.swift
import SwiftUI
/// A number with a small caption above it, for a game's score line.
public struct StatLabel: View {
let title: String
let value: Int
public init(_ title: String, value: Int) {
self.title = title
self.value = value
}
public var body: some View {
VStack(spacing: 2) {
Text(title.uppercased())
.font(.caption2.weight(.semibold))
.opacity(0.7)
Text(value, format: .number)
.font(.title2.bold().monospacedDigit())
}
}
}
Detailed breakdown
publicon the type, the initializer andbodymakes them visible to apps that importDesignSystem. A Swift type is internal to its module by default.- The initializer’s first argument has no label, so a call reads
StatLabel("Score", value: 42), the way SwiftUI’s ownText("…")does. monospacedDigit()gives every digit the same width, so the label does not shift sideways as the number changes.- There is no test for it.
StatLabelholds no logic to check: it lays out two pieces of text.CheckRowhas a test because it chooses a symbol.
Commit the shared package change on its own, as the SpriteKit article did
for CoreKit, and do it now, before Step 3. When Xcode creates a project
inside a Git repository, it stages the new project’s files (as git add
would), and a plain git commit made after that would include them:
git add Packages/DesignSystem
git commit -q -m "DesignSystem: add StatLabel"
git show --stat HEAD | tail -1
1 file changed, 22 insertions(+)
Step 3: Create the Bowler app inside the workspace
Bowler is a SwiftUI app made from Xcode’s plain App template, like Catcher. The template list also offers Augmented Reality App, which shows RealityKit content over the live camera picture; this game draws its own lane and needs no camera, so it does not use that template. Open the workspace and add the new package to it first, so the app can link it:
open MyApps.xcworkspace
- Click an empty area of the Project navigator so nothing is selected, and choose File → Add Files to “MyApps”….
- Select the
Packages/BowlingKitfolder, click Add, and in the options sheet click Finish.
Then create the app, as the SpriteKit article did for Catcher:
- Choose File → New → Project…, then Choose Template…, the iOS tab, App, and Next.
- Set Product Name to
Bowler, leave Team without an account, check that Organization Identifier readscom.example, and set Interface to SwiftUI, Language to Swift, Testing System to None and Storage to None. Click Next. - In the save panel, open
my-apps/Apps, leave Create Git repository on my Mac unchecked, set Add to and Group to MyApps, and click Create.
grep Bowl MyApps.xcworkspace/contents.xcworkspacedata
location = "group:Apps/Bowler/Bowler.xcodeproj">
location = "group:Packages/BowlingKit">
Link the three packages the game uses through Build Phases, never the General tab, which can write the display name into the target:
- Click the Bowler project in the Project navigator. If the editor opens on the target’s General tab, switch to Build Phases at once.
- With the Bowler target selected, expand Link Binary With Libraries and click +.
- Under Workspace, expand BowlingKit, select its library, and click Add. Do the same for CoreKit and DesignSystem.
grep -oE 'productName = [A-Za-z]+;|relativePath' Apps/Bowler/Bowler.xcodeproj/project.pbxproj
productName = Bowler;
productName = BowlingKit;
productName = CoreKit;
productName = DesignSystem;
The target’s own name and the three linked products, with no relativePath:
the workspace supplies the packages.
Step 4: Add Bowler to the Makefile and share its scheme
The Makefile refuses any APP it does not list, so make run,
make settings and make release cannot reach Bowler until this step adds
it. Three lines change: Bowler joins APPS, BowlingKit joins PACKAGES
(it depends on no other package, so any position works), and Bowler gets a
DEPS_ line naming the packages make changes should watch for it. The
LAUNCH_ARGS that make run passes to the app is already there from the
SpriteKit article. Edit the file with sed, then check the result:
sed -i '' \
-e 's/^APPS := TodoList Shopping Catcher$/APPS := TodoList Shopping Catcher Bowler/' \
-e 's/^PACKAGES := CoreKit DesignSystem CatcherKit TodoKit Ads$/PACKAGES := CoreKit DesignSystem CatcherKit BowlingKit TodoKit Ads/' \
-e 's/^DEPS_Catcher := CatcherKit CoreKit Ads$/&\
DEPS_Bowler := BowlingKit CoreKit DesignSystem/' Makefile
grep -E '^(APPS|PACKAGES|DEPS_)' Makefile
APPS := TodoList Shopping Catcher Bowler
PACKAGES := CoreKit DesignSystem CatcherKit BowlingKit TodoKit Ads
DEPS_TodoList := TodoKit CoreKit DesignSystem
DEPS_Shopping := CoreKit DesignSystem Ads
DEPS_Catcher := CatcherKit CoreKit Ads
DEPS_Bowler := BowlingKit CoreKit DesignSystem
make test builds each app through its scheme, and a fresh clone only has
the schemes saved in the repository. Share Bowler’s:
- Choose Product → Scheme → Bowler, then Product → Scheme → Edit Scheme….
- Check that Shared is ticked, and click Close.
find Apps -name '*.xcscheme' | sort
Apps/Bowler/Bowler.xcodeproj/xcshareddata/xcschemes/Bowler.xcscheme
Apps/Catcher/Catcher.xcodeproj/xcshareddata/xcschemes/Catcher.xcscheme
Apps/Shopping/Shopping.xcodeproj/xcshareddata/xcschemes/Shopping.xcscheme
Apps/TodoList/TodoList.xcodeproj/xcshareddata/xcschemes/TodoList.xcscheme
Step 5: Give Bowler its own version, name and icon
Like every app in the monorepo, Bowler keeps its identity and version in a
file of its own that make release reads. Without it, make release has no
version to read and the template’s target values would put version 1.0 on
the archive; without an icon, the home screen shows a blank one.
Create the file
touch Apps/Bowler/Bowler.xcconfig
Add the code: Apps/Bowler/Bowler.xcconfig
// Bowler's identity and version, for Debug and Release.
#include "../Config/Shared.xcconfig"
PRODUCT_BUNDLE_IDENTIFIER = $(BUNDLE_ID_PREFIX).Bowler
INFOPLIST_KEY_CFBundleDisplayName = Bowler
INFOPLIST_KEY_CFBundleDisplayName[config=Debug] = Bowler Dev
// The version people see. Raise it for each release.
MARKETING_VERSION = 1.0.0
// The build number. `make archive` replaces it with the commit count.
CURRENT_PROJECT_VERSION = 1
Detailed breakdown
- The same shape as Catcher’s file before ads, with Bowler’s names. It
includes
Shared.xcconfig, so Bowler also treats warnings as errors and takes its bundle identifier prefix from there. It does not includeAds.xcconfig: Bowler shows no ads. - The version starts at
1.0.0, the first of Bowler’s own release tags.
Attach the file and clear the target values, as the SpriteKit article’s Step 5 did:
- Select the Bowler project, choose File → Add Files to
“Bowler”…, select
Apps/Bowler/Bowler.xcconfig, click Add, clear the Bowler checkbox under Targets, and click Finish. - Select Bowler under PROJECT, open Info, and set the project row of both Debug and Release to Bowler.xcconfig.
- Still on the project, open Build Settings, then select the Bowler
target. With All and Levels shown, delete the target’s values for
MARKETING_VERSION,CURRENT_PROJECT_VERSION(the Current Project Version row),PRODUCT_BUNDLE_IDENTIFIER, andCFBundleDisplayNameif the target column has one.
grep -o 'baseConfigurationReference.*' Apps/Bowler/Bowler.xcodeproj/project.pbxproj
grep -cE 'MARKETING_VERSION|CURRENT_PROJECT_VERSION|PRODUCT_BUNDLE_IDENTIFIER|CFBundleDisplayName' Apps/Bowler/Bowler.xcodeproj/project.pbxproj
make settings APP=Bowler CONFIG=Release
baseConfigurationReference = 308498F53090D2A100209F7C /* Bowler.xcconfig */;
baseConfigurationReference = 308498F53090D2A100209F7C /* Bowler.xcconfig */;
0
CONFIGURATION = Release
CURRENT_PROJECT_VERSION = 1
INFOPLIST_KEY_CFBundleDisplayName = Bowler
MARKETING_VERSION = 1.0.0
PRODUCT_BUNDLE_IDENTIFIER = com.example.Bowler
SWIFT_TREAT_WARNINGS_AS_ERRORS = YES
Both configurations use the file, the target sets none of the four values,
and every value shown comes from Bowler.xcconfig or Shared.xcconfig. The
identifier on each baseConfigurationReference line differs in your project.
Draw the icon, an indigo B, and give the image set the same Contents.json
as the other apps:
swift Tools/make-icon.swift B 0.35 0.34 0.84 Apps/Bowler/Bowler/Assets.xcassets/AppIcon.appiconset/AppIcon.png
cp Apps/Shopping/Shopping/Assets.xcassets/AppIcon.appiconset/Contents.json Apps/Bowler/Bowler/Assets.xcassets/AppIcon.appiconset/
Step 6: Keep the game’s state where SwiftUI can see it
The 3D scene (the Lane class Step 8 writes) records each roll, and
SwiftUI draws the frame, score and best
score above it, so both need the same state. GameSession holds it, as Catcher’s
did: the current BowlingGame and the best score, in an @Observable
class whose changes SwiftUI shows. The file goes into
Apps/Bowler/Bowler/, the app’s synchronized folder, so Xcode adds it to
the target with no extra step.
Create the file
touch Apps/Bowler/Bowler/GameSession.swift
Add the code: Apps/Bowler/Bowler/GameSession.swift
import BowlingKit
import CoreKit
import Observation
/// The state the lane changes and the SwiftUI overlay shows.
@Observable
final class GameSession {
private(set) var game = BowlingGame()
private(set) var best: Int
private let bestScore = BestScore(key: "bestGame")
init() {
best = bestScore.value
}
func roll(_ pins: Int) {
game.roll(pins)
if game.isOver, bestScore.record(game.score) {
best = game.score
}
}
func restart() {
game = BowlingGame()
}
}
Detailed breakdown
roll(_:)forwards to the rules, so the scene never sets the score; the testedBowlingGamedoes.- The best score is recorded only when a game ends. A bowling score is
not final until the tenth frame, because bonuses are added later, so
recording mid-game would keep scores that were never finished.
BestScorefromCoreKitkeeps it inUserDefaultsunder its own key,bestGame. bestis a copy for SwiftUI to observe, because@Observablecannot watchUserDefaults.
Step 7: Write a custom component and system
RealityKit organizes a scene as entities (Entity and its subclasses),
each a thing in the scene with a position, a rotation and a scale, arranged
in a tree of parents and children. What an entity is comes from its
components, values attached to it: a ModelComponent gives it a shape and
materials (surface color and finish) to draw, a CollisionComponent a shape
that collides, a PhysicsBodyComponent mass and a response to gravity, which
makes the entity a physics body. You can write your own
component, any struct that conforms to Component, to attach your own data.
Behavior that must run continuously goes in a system, a type RealityKit
calls each time it updates the scene, once per redraw; the system finds the
entities that carry a given component and acts on them.
Bowler needs one of each. The physics engine makes a pin fall, but nothing
in it counts a pin as knocked down. PinComponent marks an entity as
a pin and records whether it is down, and PinSystem checks every standing
pin on every update and marks the ones that have tipped over or fallen off
the lane. RealityKit measures in meters, with y pointing up, and the
lane’s top surface is at y = 0.
Create the file
touch Apps/Bowler/Bowler/PinSystem.swift
Add the code: Apps/Bowler/Bowler/PinSystem.swift
import RealityKit
/// Marks an entity as a pin. `PinSystem` sets `isDown` once the pin falls.
struct PinComponent: Component {
var isDown = false
}
/// Runs each time RealityKit updates the scene, once per redraw of the
/// screen, and marks the pins that have fallen since the last update.
struct PinSystem: System {
private static let pins = EntityQuery(where: .has(PinComponent.self))
init(scene: Scene) {}
func update(context: SceneUpdateContext) {
for pin in context.entities(matching: Self.pins, updatingSystemWhen: .rendering) {
guard var state = pin.components[PinComponent.self], !state.isDown else { continue }
// The pin's own "up" direction, in the scene's coordinates.
let up = pin.orientation(relativeTo: nil).act([0, 1, 0])
// Tipped more than about 45 degrees, or fallen off the end of the lane.
if up.y < 0.7 || pin.position(relativeTo: nil).y < -0.1 {
state.isDown = true
pin.components.set(state)
pin.components.set(OpacityComponent(opacity: 0.35))
}
}
}
}
Detailed breakdown
PinComponentis a plain struct. Conforming toComponentis all it takes to attach one to an entity withentity.components.set(...)and read it back withentity.components[PinComponent.self]. Components are values, so changingisDownmeans reading the component, changing the copy, and setting it again, asupdate(context:)does.EntityQuery(where: .has(PinComponent.self))selects every entity carrying the component, wherever it is in the tree. The query is built once, as astatic let, and run on each update withcontext.entities(matching:updatingSystemWhen:). The.renderingcondition tells RealityKit to keep calling the system while the scene is drawn.- “Down” is a measurement.
orientation(relativeTo: nil)is the pin’s rotation in the scene’s coordinates;act([0, 1, 0])applies it to a vector pointing straight up, giving the direction the pin’s own top now points. For an upright pin itsyis 1, andyshrinks as the pin tips: below 0.7, the pin is more than about 45 degrees over (cos 45° ≈ 0.707). A pin whose center has dropped below -0.1 meters has fallen off the end of the lane, which also counts. - A fallen pin turns see-through.
OpacityComponent(opacity: 0.35)draws it at 35% opacity, so you can see which pins counted while they settle. A pin marked down stays down: theguardskips it from then on. - The system has an empty
init(scene:). RealityKit creates the system itself, once per scene, and requires this initializer.
RealityKit has to know about a custom component and system before a scene uses them. Register both when the app starts.
Create the file
touch Apps/Bowler/Bowler/BowlerApp.swift
The file exists already. Replace its contents with the listing below.
Add the code: Apps/Bowler/Bowler/BowlerApp.swift
import RealityKit
import SwiftUI
@main
struct BowlerApp: App {
init() {
// RealityKit must know about a custom component and system before
// any scene uses them.
PinComponent.registerComponent()
PinSystem.registerSystem()
}
var body: some SwiftUI.Scene {
WindowGroup {
ContentView()
}
}
}
Detailed breakdown
registerComponent()andregisterSystem()run in the app’sinit, before the first view, and so before any scene exists.- The file imports RealityKit because it calls RealityKit methods. The
template turns on member import visibility, so without the import the build
fails with
static method 'registerComponent()' is not available due to missing import of defining module 'RealityKit'. bodyreturnssome SwiftUI.Scene, notsome Scene. RealityKit also has a type calledScene(the root of a 3D scene), and with both modules imported the bare name fails with'Scene' is ambiguous for type lookup in this context. Naming the module picks SwiftUI’s.
Step 8: Build the lane
Lane builds every entity in the scene and runs the game around them: it
rolls the ball, notices when the ball reaches the end, counts the pins
PinSystem marked, and resets for the next roll. The camera looks toward
negative z, so the ball starts at the origin and rolls toward z = -5,
where the head pin (the front pin) stands. The ball and pins are close to
real sizes; the lane is shortened to about a quarter of a real one’s 18
meters, so the camera can see the pins.
Create the file
touch Apps/Bowler/Bowler/Lane.swift
Add the code: Apps/Bowler/Bowler/Lane.swift
import BowlingKit
import Foundation
import RealityKit
import UIKit
/// The bowling lane: builds the entities, rolls the ball, and counts the
/// pins each roll knocks down. Distances are in meters, as in RealityKit.
final class Lane {
static let ballRadius: Float = 0.11
static let ballMass: Float = 7
static let pinHeight: Float = 0.38
static let headPinZ: Float = -5
/// Holds every entity in the scene, so the view adds just this one.
let root = Entity()
let ball: ModelEntity
/// The collision subscription, kept for as long as the lane exists.
var collisions: EventSubscription?
private enum Phase { case ready, rolling, counting }
private var phase = Phase.ready
/// Counts rolls, so a timeout can tell whether its roll is still going.
private var rollNumber = 0
private var pins: [ModelEntity] = []
/// Where the ball was when the current drag began.
private var dragStartX: Float?
private let session: GameSession
/// Launch with `-autoplay YES` to let the game bowl by itself.
private let autoplay = UserDefaults.standard.bool(forKey: "autoplay")
private let slippery = PhysicsMaterialResource.generate(
staticFriction: 0.1, dynamicFriction: 0.05, restitution: 0.3)
init(session: GameSession) {
self.session = session
let shape = ShapeResource.generateSphere(radius: Self.ballRadius)
ball = ModelEntity(
mesh: .generateSphere(radius: Self.ballRadius),
materials: [SimpleMaterial(color: .systemIndigo, roughness: 0.2, isMetallic: false)])
ball.components.set(CollisionComponent(shapes: [shape]))
ball.components.set(PhysicsBodyComponent(
shapes: [shape], mass: Self.ballMass, material: slippery, mode: .dynamic))
// Gestures reach only entities with an input target and a collision shape.
ball.components.set(InputTargetComponent())
buildLane()
root.addChild(ball)
resetBall()
setUpPins()
}
var canRoll: Bool { phase == .ready && !session.game.isOver }
/// Starts autoplay, if it is on. Called once the scene is showing.
func start() {
rollByItselfIfAutoplay()
}
func newGame() {
session.restart()
setUpPins()
resetBall()
phase = .ready
rollByItselfIfAutoplay()
}
// MARK: Building the scene
private func buildLane() {
let wood = SimpleMaterial(color: UIColor(red: 0.85, green: 0.65, blue: 0.40, alpha: 1),
roughness: 0.4, isMetallic: false)
let rail = SimpleMaterial(color: .systemGray, roughness: 0.6, isMetallic: false)
// The lane runs from z = 0.5 to z = -6.1, with its top surface at y = 0.
root.addChild(block(size: [1.1, 0.1, 6.6], at: [0, -0.05, -2.8], material: wood))
// Bumpers along both edges keep every roll on the lane.
for side: Float in [-1, 1] {
root.addChild(block(size: [0.1, 0.25, 6.6], at: [0.6 * side, 0.075, -2.8], material: rail))
}
// The pit: an invisible trigger past the end of the lane. It reports
// the ball entering it but does not stop anything.
let pit = Entity()
pit.name = "pit"
pit.position = [0, -1.5, -8]
pit.components.set(CollisionComponent(
shapes: [.generateBox(width: 6, height: 2.6, depth: 4)], mode: .trigger))
root.addChild(pit)
let sun = DirectionalLight()
sun.light.intensity = 3000
sun.shadow = DirectionalLightComponent.Shadow(maximumDistance: 12, depthBias: 2)
sun.look(at: [0, 0, -4], from: [1, 4, 1], relativeTo: nil)
root.addChild(sun)
let camera = PerspectiveCamera()
camera.camera.fieldOfViewInDegrees = 35
camera.look(at: [0, 0, -3.5], from: [0, 1.4, 3.0], relativeTo: nil)
root.addChild(camera)
}
/// A box that never moves but that other bodies collide with.
private func block(size: SIMD3<Float>, at position: SIMD3<Float>,
material: SimpleMaterial) -> ModelEntity {
let entity = ModelEntity(mesh: .generateBox(size: size), materials: [material])
entity.position = position
let shape = ShapeResource.generateBox(size: size)
entity.components.set(CollisionComponent(shapes: [shape]))
entity.components.set(PhysicsBodyComponent(
shapes: [shape], mass: 0, material: slippery, mode: .static))
return entity
}
/// Removes any pins left and sets up ten in a triangle, head pin nearest
/// the ball, 0.3 meters apart.
private func setUpPins() {
for pin in pins { pin.removeFromParent() }
pins = []
let white = SimpleMaterial(color: .white, roughness: 0.3, isMetallic: false)
// A box shape stands steadier than a round one and is close enough.
let shape = ShapeResource.generateBox(width: 0.12, height: Self.pinHeight, depth: 0.12)
for row in 0..<4 {
for place in 0...row {
let pin = ModelEntity(
mesh: .generateCylinder(height: Self.pinHeight, radius: 0.06),
materials: [white])
pin.position = [(Float(place) - Float(row) / 2) * 0.3,
Self.pinHeight / 2,
Self.headPinZ - Float(row) * 0.26]
pin.components.set(CollisionComponent(shapes: [shape]))
pin.components.set(PhysicsBodyComponent(
shapes: [shape], mass: 1.5, material: slippery, mode: .dynamic))
pin.components.set(PinComponent())
root.addChild(pin)
pins.append(pin)
}
}
}
private func resetBall() {
ball.position = [0, Self.ballRadius, 0]
ball.orientation = simd_quatf(angle: 0, axis: [0, 1, 0])
// A new motion component has zero velocity, so the ball stops dead.
ball.components.set(PhysicsMotionComponent())
}
// MARK: Rolling
/// Rolls the ball down the lane at `speed` meters a second, drifting
/// sideways at `drift` meters a second.
func roll(speed: Float = 7, drift: Float = 0) {
guard canRoll else { return }
phase = .rolling
rollNumber += 1
let thisRoll = rollNumber
// An impulse is mass times the change in velocity.
ball.applyLinearImpulse([drift, 0, -speed] * Self.ballMass, relativeTo: nil)
// If the ball stops short of the pit, end the roll anyway.
Task {
try? await Task.sleep(for: .seconds(6))
if phase == .rolling, rollNumber == thisRoll {
await countPins()
}
}
}
/// Moves the resting ball sideways with a finger, `width` points from
/// where the drag began.
func slide(by width: CGFloat) {
guard canRoll else {
dragStartX = nil
return
}
let startX = dragStartX ?? ball.position.x
dragStartX = startX
ball.position.x = min(max(startX + Float(width) / 250, -0.38), 0.38)
}
/// Ends a drag. A quick flick up the screen rolls the ball. How far
/// SwiftUI predicts the finger would have gone on after letting go
/// measures how fast it was moving, and sets the speed and drift.
func release(predictedEnd: CGSize, translation: CGSize) {
dragStartX = nil
let flick = Float(translation.height - predictedEnd.height)
guard flick > 50 else { return }
let drift = Float(predictedEnd.width - translation.width) / 400
roll(speed: min(max(flick / 40, 3), 9), drift: min(max(drift, -0.5), 0.5))
}
/// Called by RealityKit when the ball starts touching another entity.
func ballHit(_ event: CollisionEvents.Began) {
guard phase == .rolling, event.entityA.name == "pit" || event.entityB.name == "pit" else { return }
Task { await countPins() }
}
/// Waits for the pins to settle, records the roll, then clears the
/// fallen pins or sets up a full set, as the rules say.
private func countPins() async {
guard phase == .rolling else { return }
phase = .counting
try? await Task.sleep(for: .seconds(1.5))
let down = pins.filter { $0.components[PinComponent.self]?.isDown == true }
session.roll(down.count)
if session.game.pinsStanding == BowlingGame.pinCount {
setUpPins()
} else {
for pin in down { pin.removeFromParent() }
pins.removeAll { pin in down.contains { $0 === pin } }
}
resetBall()
phase = .ready
rollByItselfIfAutoplay()
}
private func rollByItselfIfAutoplay() {
guard autoplay else { return }
Task {
try? await Task.sleep(for: .seconds(1))
roll(drift: .random(in: -0.15...0.15))
}
}
}
Detailed breakdown
The ball.
- A
ModelEntityis an entity that draws a mesh, the triangles that make up a visible surface.MeshResource.generateSpheremakes the geometry andSimpleMaterialthe surface: a color, how rough it looks, and whether it is metal. No 3D model file is involved. - The ball gets three more components.
CollisionComponentgives it a collision shape, a simpleShapeResourcethe physics engine tests instead of the drawn mesh.PhysicsBodyComponentgives it a mass of 7 kilograms, a physics material and the.dynamicmode, meaning gravity and collisions move it.InputTargetComponentmakes it able to receive gestures; Step 9’s gestures find only entities that have both this and a collision shape. - The physics material is slippery.
PhysicsMaterialResource.generatesets friction (resistance to sliding) and restitution (bounciness). Low friction keeps a slow roll moving to the pins.
The lane, pit, light and camera.
block(size:at:material:)makes the fixed parts: a box with a collision shape and a.staticphysics body, which other bodies collide with but which never moves. The lane is a 1.1-meter-wide box whose top is aty = 0; the bumpers along its edges are rails that keep every roll on the lane, like the bumpers children bowl with. The back corner pins clear the rails by 4 centimeters.- The pit is a trigger. It is an entity with a collision shape and no
model, so it is invisible, and its
CollisionComponentuses.triggermode: it reports anything that enters it but pushes nothing back. It sits below and beyond the end of the lane, where the ball falls after passing the pins. That is how the game knows a roll is over. DirectionalLightis sunlight: light from one direction, equally bright everywhere.look(at:from:relativeTo:)points it down the lane from above and to the right, and itsShadowmakes the ball and pins cast shadows.maximumDistancelimits how far away shadows are drawn, anddepthBiasoffsets the shadow test so surfaces do not speckle with their own shadow.relativeTo: nilmeans the positions are in the scene’s coordinates.PerspectiveCamerais the viewpointRealityViewdraws from. It sits 1.4 meters up and 3 meters behind the ball, looking at a point 3.5 meters down the lane, with a 35-degree field of view (how wide an angle it sees).
The pins.
setUpPins()removes any pins and makes ten new ones, in four rows of 1, 2, 3 and 4. Pins in a row are 0.3 meters apart, as on a real lane, and each row is 0.26 meters farther back (0.3 × sin 60°), so the pins form equilateral triangles.- Each pin draws as a cylinder but collides as a box. A box stands
steadily on its flat base and is close enough for a pin 12 centimeters
wide. Each pin carries a
PinComponent, which is whatPinSystem’s query finds.
Rolling.
Phasekeeps the game to one roll at a time:readywaits for input,rollingwaits for the ball to reach the pit, andcountingwaits for the pins to settle.canRollis true only when ready and the game is not over, so taps during a roll do nothing.roll(speed:drift:)pushes the ball with an impulse.applyLinearImpulsechanges a body’s momentum, which is mass times velocity, so multiplying the wanted velocity by the ball’s mass makes it start at exactlyspeedmeters a second down the lane (negative z) anddriftmeters a second sideways. A tap rolls at 7 m/s, a little under a typical bowler’s 8.- A timeout ends a roll that never reaches the pit.
rollNumberlets the task check, six seconds later, that the roll it was started for is still the current one. slide(by:)andrelease(predictedEnd:translation:)turn a drag into a roll. While your finger moves, the ball follows it sideways, 1 meter for every 250 points of drag, kept between the bumpers. When you let go, SwiftUI’spredictedEndTranslationsays where the finger would have come to rest with its speed. Its distance past where the finger actually let go measures the flick: more than 50 points up the screen rolls the ball, faster for a harder flick (between 3 and 9 m/s), and the sideways part becomes drift. A finger that stops before letting go predicts no further travel, so a slow drag in any direction just leaves the ball where you put it. A drag does nothing while a roll is under way.
Counting.
ballHit(_:)receives collision events. Step 9 subscribes it toCollisionEvents.Began, which RealityKit sends when two collision shapes start touching. The event names the two entities, and the only one that matters here is the pit.countPins()waits 1.5 seconds for the pins to settle, then counts the onesPinSystemmarked as down and records that as the roll. If the game now says 10 pins are standing, a new frame (or a tenth-frame extra roll) has started, so it sets up a full set; otherwise it removes only the fallen pins, leaving the standing ones exactly where they ended up. Then it puts the ball back.resetBall()stands the ball upright and stops it. An angle of 0 about any axis is no rotation. A newPhysicsMotionComponent, the component that holds a body’s velocity, has zero velocity, so the ball does not carry its old speed back to the start.autoplaycomes from the-autoplay YESlaunch argument, read fromUserDefaultsas in Catcher. When it is on, the lane rolls by itself a second after it is ready, with a random drift, which is how a screenshot can show a game in progress.- Every type in the app runs on the main actor (the template sets
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor), and RealityKit’sSystemrequires its methods to run there too, soLane,PinSystemand SwiftUI share state without locks. TheTasks that wait run on the main actor as well.
Step 9: Show the scene in SwiftUI
RealityView is the SwiftUI view that shows RealityKit content. Its
closure runs once, when the view appears, and adds entities to the view’s
content, the collection it draws. On
iOS, gestures attach to the view and are aimed at entities with
targetedToEntity(_:). The template’s ContentView becomes the game screen:
the scene filling the display, the score line on top, and a game-over panel.
Create the file
touch Apps/Bowler/Bowler/ContentView.swift
The file exists already. Replace its contents with the listing below.
Add the code: Apps/Bowler/Bowler/ContentView.swift
import BowlingKit
import DesignSystem
import RealityKit
import SwiftUI
struct ContentView: View {
@State private var session: GameSession
@State private var lane: Lane
init() {
let session = GameSession()
_session = State(initialValue: session)
_lane = State(initialValue: Lane(session: session))
}
var body: some View {
RealityView { content in
content.add(lane.root)
lane.collisions = content.subscribe(
to: CollisionEvents.Began.self, on: lane.ball) { [lane] event in
lane.ballHit(event)
}
lane.start()
}
.gesture(TapGesture().targetedToEntity(lane.ball).onEnded { _ in
lane.roll()
})
.simultaneousGesture(DragGesture().targetedToEntity(lane.ball)
.onChanged { value in
lane.slide(by: value.translation.width)
}
.onEnded { value in
lane.release(predictedEnd: value.predictedEndTranslation,
translation: value.translation)
})
.ignoresSafeArea()
.background(Color(red: 0.10, green: 0.12, blue: 0.25))
.overlay(alignment: .top) {
HStack {
StatLabel("Frame", value: session.game.frameNumber)
Spacer()
StatLabel("Score", value: session.game.score)
Spacer()
StatLabel("Best", value: session.best)
}
.padding(.horizontal, 32)
.foregroundStyle(.white)
.allowsHitTesting(false)
}
.overlay {
if session.game.isOver {
VStack(spacing: 16) {
Text("Game over: \(session.game.score)")
.font(.title.bold())
Button("New game") { lane.newGame() }
.buttonStyle(.borderedProminent)
}
.padding(24)
.background(.ultraThinMaterial, in: .rect(cornerRadius: 16))
}
}
}
}
#Preview {
ContentView()
}
Detailed breakdown
- The session and the lane are
@State, set up ininit, as Catcher’s session and scene were, so SwiftUI keeps the first ones however often it recreates the view. The lane receives the session the overlay reads. content.add(lane.root)puts the whole scene in the view. Every entity, the camera and light included, is a child ofroot.content.subscribe(to:on:)delivers collision events. It calls the closure for eachCollisionEvents.Beganthat involveslane.ball, and returns a subscription, whichLanekeeps incollisionsfor as long as the lane exists.[lane]captures the lane itself rather than the view.- The tap and the drag are both aimed at the ball.
TapGesture().targetedToEntity(lane.ball)fires only for a tap on the ball, and the drag only for a drag that starts on it. The drag is attached withsimultaneousGestureso neither blocks the other. A tap moves the finger less than the drag’s 10-point minimum, so it does not start a drag, and if both ever fired,canRollwould ignore the second roll. - The background color shows through.
RealityViewdraws nothing where no entity is, so the dark blue behind it is the sky. Without.background, it would be the system background, white in light mode, and the white score line on top would disappear. - The score line ignores touches (
allowsHitTesting(false)), so a finger on it still reaches the scene. The game-over panel does take touches: its New game button callslane.newGame(), which restarts the session, sets up the pins and resets the ball. import BowlingKitis needed because the view readsframeNumber,scoreandisOver, members ofBowlingGame, under member import visibility.
Build every app:
make build
--- TodoList
--- Shopping
--- Catcher
--- Bowler
The build treats warnings as errors, so no output after the app names means the new code compiled without a warning.
Step 10: Bowl a game
Start with autoplay, so the run shows the scene, the physics and the scoring working without input. Give it a few seconds, then take a screenshot:
make run APP=Bowler LAUNCH_ARGS="-autoplay YES"
sleep 15
make screenshot APP=Bowler
xcrun simctl launch "TodoList-iPhone" com.example.Bowler -autoplay YES
com.example.Bowler: 9761
xcrun simctl io "TodoList-iPhone" screenshot screenshots/Bowler.png
Detected file type from extension: PNG
Note: No display specified. Defaulting to display: C9CCD061-CC6B-4FFA-9052-1B84AC8E8AA8 (screenID: 1, name: LCD)
The first two lines are the end of make run’s output; the process ID and
display identifier differ on your Mac, and make screenshot’s last line
(the full path) is left out. screenshots/Bowler.png shows the lane in
perspective under a dark blue sky, with FRAME, SCORE and BEST
across the top. In the validation run it showed frame 3 with a score of 19,
and pins tumbling, some already faded, after the ball had passed.
Your numbers will differ, because autoplay aims with a random drift and the
physics plays out a little differently each time.
Leave it running. A game of ten frames takes autoplay one to two minutes;
then a panel shows Game over with the final score, and BEST shows the
same number (190 and 159 in two validation runs). make screenshot always
writes screenshots/Bowler.png, so keep a copy of the first one, then take
another:
cp screenshots/Bowler.png screenshots/Bowler-early.png
sleep 120
make screenshot APP=Bowler
Now bowl yourself. Quit and relaunch without autoplay:
xcrun simctl terminate TodoList-iPhone com.example.Bowler
make run APP=Bowler
In the simulator window, a click is a tap and a click-and-drag is a drag:
- Click the ball. It rolls straight down the middle at 7 m/s, the pins scatter, fallen ones fade, and about a second and a half after the ball drops into the pit the score updates. Then the fallen pins disappear and the ball comes back. A strike moves straight to the next frame with ten new pins.
- Drag the ball slowly sideways and let go. It follows the pointer and stays where you leave it.
- Flick it up the screen: press on the ball, move quickly upward and release while still moving. It rolls from where it sits, faster for a harder flick, at a slight angle if the flick leaned sideways. A slow drag upward that stops before you let go does not roll it.
Ten frames later the game-over panel appears; New game starts again at frame 1, and BEST keeps your highest score across games and launches.
Finally, run the whole suite. make test now tests BowlingKit and builds
Bowler with the other apps:
make test 2>&1 | grep -E '^---|Test run|TEST'
--- CoreKit
✔ Test run with 5 tests in 2 suites passed after 0.003 seconds.
--- DesignSystem
✔ Test run with 2 tests in 1 suite passed after 0.025 seconds.
--- CatcherKit
✔ Test run with 6 tests in 1 suite passed after 0.001 seconds.
--- BowlingKit
✔ Test run with 4 tests in 1 suite passed after 0.001 seconds.
--- TodoKit
✔ Test run with 5 tests in 1 suite passed after 0.011 seconds.
--- Ads
✔ Test run with 3 tests in 2 suites passed after 0.001 seconds.
--- TodoList
--- Shopping
--- Catcher
--- Bowler
--- TodoList UI tests
** TEST SUCCEEDED **
Timings vary from run to run.
Step 11: Release Bowler
Bowler ships the way the other apps do: commit, then make release. The
DesignSystem change was committed in Step 2; commit the rest:
git add -A
git commit -q -m "Add the Bowler game"
make release APP=Bowler
xcodebuild -workspace MyApps.xcworkspace -derivedDataPath build -scheme Bowler -destination 'generic/platform=iOS' -archivePath build/Bowler.xcarchive CURRENT_PROJECT_VERSION=16 CODE_SIGNING_ALLOWED=NO -quiet archive
{"CFBundleShortVersionString":"1.0.0","CFBundleIdentifier":"com.example.Bowler","Team":"","ApplicationPath":"Applications\/Bowler.app","SigningIdentity":"","Architectures":["arm64"],"CFBundleVersion":"16"}
git tag -a Bowler/v1.0.0 -m "Bowler 1.0.0 (build 16)"
Build 16: the 14 commits from the previous article, plus the two made here. Now ask what each app has waiting:
make changes APP=TodoList
make changes APP=Shopping
make changes APP=Catcher
make changes APP=Bowler
TodoList since TodoList/v1.0.1:
97686bb DesignSystem: add StatLabel
f48f9e4 CoreKit: add BestScore
Shopping since Shopping/v1.2.0:
97686bb DesignSystem: add StatLabel
Catcher since Catcher/v1.1.0:
(no changes)
Bowler since Bowler/v1.0.0:
(no changes)
Your hashes differ. TodoList and Shopping list the DesignSystem commit
because both are built from DesignSystem; neither uses StatLabel, so
neither looks or behaves differently, and the decision whether to release
them stays yours, as it did for the CoreKit commit TodoList has carried
since the SpriteKit article. Catcher is built without DesignSystem, so the
commit does not appear for it at all.
Troubleshooting
'Scene' is ambiguous for type lookup in this contextinBowlerApp.swift. RealityKit and SwiftUI both defineScene; writesome SwiftUI.Scene.… is not available due to missing import of defining module 'RealityKit'(or'BowlingKit'). Add the import to the file that uses the member; the template’s member import visibility requires it per file.APP must be one of TodoList Shopping Catcher. Step 4’sseddid not match. Check theAPPSline withgrep '^APPS' Makefile; the spacing must be as shown.- Tapping or dragging the ball does nothing. A gesture targets only an
entity with both an
InputTargetComponentand aCollisionComponent; check both are set on the ball. A tap during a roll is ignored on purpose. - The ball reaches the end but the score never changes. The pit’s
collision event did not arrive, and the six-second timeout is ending each
roll instead. Check that the pit’s name is
pitand thatcontent.subscribeis called withon: lane.ball. - Pins fall but do not fade, and every roll scores 0.
PinSystemis not running. Check thatBowlerApp’sinitcallsPinSystem.registerSystem(). - The app stops with
Only 3 pins are standing. More pins were counted thanBowlingGamethinks are standing, so the lane’s pins and the game disagree. Check thatcountPins()removes the fallen pins frompinsas well as from the scene.
Recap
The monorepo now holds a 3D game built with the same structure as its other
apps. Bowler’s rules are a BowlingGame value in the BowlingKit package,
tested on the Mac with no scene; its best score comes from CoreKit’s
BestScore, and its score line from a new StatLabel in DesignSystem.
The scene is entities with components: generated meshes and simple materials
to draw, collision shapes and physics bodies for the ball, pins, lane and
bumpers, a trigger that ends each roll through a collision event, a
directional light with shadows, and a perspective camera. A custom
PinComponent and PinSystem turn physics into bowling by marking fallen
pins on every update. RealityView shows the scene in SwiftUI, a tap
and a flick aimed at the ball roll it, and make release APP=Bowler produced
Bowler/v1.0.0 at build 16.
Next improvements:
- Add sound with an
AudioFileResourceplayed from the ball whenCollisionEvents.Beganreports a pin. - Give Bowler a UI test that launches it with
-autoplay YESand waits for the game-over panel, and add it toUI_TESTED. - Show a full scorecard, one box per frame, from
BowlingGame.frames.