Capturing Body Motion in 3D
At a glance
| Item | Summary |
|---|---|
| Purpose | Track a person with ARBodyTrackingConfiguration and drive a rigged RealityKit character (BodyTrackedEntity) that follows the body anchor. |
| App architecture | UIKit scene-based shell (AppDelegate + SceneDelegate + Main.storyboard) hosting one ViewController that owns the ARView, runs the session, and receives ARSessionDelegate callbacks. |
| Main patterns | ARKit session delegate callbacks; a self-cancelling Combine subscription for asynchronous model loading. |
| Project style | Three Swift files in one app target; the storyboard creates the controller and its ARView. |
| Execution model | No explicit actor, queue, or task; work happens in UIKit lifecycle methods, an ARKit delegate callback, and Combine sink closures. |
| State/event model | Direct mutation of characterAnchor and character from callbacks. |
| Key frameworks/packages | UIKit, RealityKit, ARKit, Combine; no package manifest. |
Project structure
BodyDetection/
├── AppDelegate.swift app delegate, scene configuration
├── SceneDelegate.swift window scene delegate (empty lifecycle hooks)
├── ViewController.swift ARView owner, session delegate
├── Base.lproj/Main.storyboard initial ViewController + ARView outlet
├── character/ robot USDZ asset
└── Info.plist UIApplicationSceneManifest
Structure observations
Info.plistdeclares a single-scene manifest whose default configuration namesSceneDelegateand theMainstoryboard (BodyDetection/Info.plist:61).- All feature logic is in
ViewController.swift; the app and scene delegates carry no feature code.
Overall architecture
flowchart LR
App["AppDelegate"] -->|UISceneConfiguration| Scene["SceneDelegate"]
Scene -->|Main storyboard| VC["ViewController"]
VC --> ARView["ARView (outlet)"]
ARView --> Session["ARSession"]
Session -->|"session(_:didUpdate:)"| VC
VC --> Anchor["characterAnchor"]
VC -->|loadBodyTrackedAsync| Character["BodyTrackedEntity"]
Anchor --> Character
Reference code
BodyDetection/AppDelegate.swift:24 — AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// ...
func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
// ...
}Interpretation
The app delegate only returns the named scene configuration; the storyboard listed in that configuration instantiates ViewController and an ARView connected to its arView outlet (BodyDetection/Base.lproj/Main.storyboard:13). SceneDelegate.scene(_:willConnectTo:options:) just checks for a UIWindowScene (BodyDetection/SceneDelegate.swift:15), so the storyboard, not code, builds the window contents.
Ownership and state
classDiagram
ViewController o-- ARView : IBOutlet arView
ViewController *-- AnchorEntity : characterAnchor
ViewController o-- BodyTrackedEntity : character (set after load)
ARView *-- ARSession : session
ARSession --> ViewController : delegate
AnchorEntity *-- BodyTrackedEntity : addChild
Ownership evidence
BodyDetection/ViewController.swift:20 — stored properties
class ViewController: UIViewController, ARSessionDelegate {
@IBOutlet var arView: ARView!
// The 3D character to display.
var character: BodyTrackedEntity?
let characterOffset: SIMD3<Float> = [-1.0, 0, 0] // Offset the character by one meter to the left
let characterAnchor = AnchorEntity()
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
Storyboard / ViewController |
arView |
Created by the storyboard, held by an implicitly unwrapped outlet | — |
ViewController |
characterAnchor |
Creates and retains; added to arView.scene in viewDidAppear |
session(_:didUpdate:) sets position and orientation |
ViewController |
character |
Assigned in the load subscription’s receiveValue |
Load closure; then parented once in the delegate callback |
ViewController |
characterOffset |
Immutable value | — |
arView.session |
delegate reference to ViewController |
Assigned in viewDidAppear (BodyDetection/ViewController.swift:24) |
— |
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Framework callback | ARSessionDelegate.session(_:didUpdate:) |
Per-frame anchor updates mutate characterAnchor; the source sets no delegateQueue, so the callback queue is framework-defined |
BodyDetection/ViewController.swift:59 |
| Asynchronous load | Entity.loadBodyTrackedAsync(named:) + sink |
Publisher delivers the loaded entity or failure; no receive(on:) is applied |
BodyDetection/ViewController.swift:40 |
| Subscription lifetime | Local var cancellable captured by both closures |
The closures retain the subscription until they call cancel() |
BodyDetection/ViewController.swift:45 |
| Shared-state safety | None declared | character is written in the load closure and read in the delegate callback without a lock or actor |
BodyDetection/ViewController.swift:70 |
Reference code
BodyDetection/ViewController.swift:51 — self-cancelling load subscription
var cancellable: AnyCancellable? = nil
cancellable = Entity.loadBodyTrackedAsync(named: "character/robot").sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
print("Error: Unable to load model: \(error.localizedDescription)")
}
cancellable?.cancel()
}, receiveValue: { (character: Entity) in
if let character = character as? BodyTrackedEntity {
// Scale the character to human size
character.scale = [1.0, 1.0, 1.0]
self.character = character
cancellable?.cancel()
} else {
print("Error: Unable to load model as BodyTrackedEntity")
}
}
)Inference: capturing the local cancellable keeps the subscription alive without a stored property; the closures also capture self strongly until the load finishes.
State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | ARKit delegate callback | Body-anchor transform copied to characterAnchor each update |
BodyDetection/ViewController.swift:65 |
| State propagation | Combine sink |
One-shot delivery of the loaded character | BodyDetection/ViewController.swift:46 |
| Combine scheduling | none | No receive(on:) or subscribe(on:) |
BodyDetection/ViewController.swift:40 |
| Framework import | RealityKit, ARKit, Combine |
Compilation dependencies of the controller | BodyDetection/ViewController.swift:9 |
| Scene lifecycle | UIApplicationSceneManifest |
Single scene, SceneDelegate, Main storyboard |
BodyDetection/Info.plist:49 |
Class and protocol design
classDiagram
class ARSessionDelegate {
<<protocol>>
}
class UIWindowSceneDelegate {
<<protocol>>
}
ViewController ..|> ARSessionDelegate
SceneDelegate ..|> UIWindowSceneDelegate
AppDelegate --> SceneDelegate : configuration name
Reference code
BodyDetection/SceneDelegate.swift:10 — SceneDelegate
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard (scene as? UIWindowScene) != nil else { return }
}
// ...
}| Type | Responsibility | Depends on |
|---|---|---|
AppDelegate |
Supplies the default scene configuration | UIApplicationDelegate |
SceneDelegate |
Holds the scene window; lifecycle hooks are empty | UIWindowSceneDelegate |
ViewController |
Session setup, character loading, anchor updates | ARView, ARSessionDelegate, BodyTrackedEntity |
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ViewController.arView |
implicit internal, @IBOutlet |
Storyboard connects it; any module code could reassign it | Inference: standard outlet visibility in a single-target app |
ViewController.character |
implicit internal var |
Mutable from the load closure and delegate callback | Inference: no encapsulation needed for one controller |
characterOffset, characterAnchor |
implicit internal let |
Bindings cannot be reassigned; the anchor’s properties remain mutable | Inference: fixed offset and one long-lived anchor |
No private, fileprivate, or public modifiers appear in the three Swift files.
Reference code
BodyDetection/ViewController.swift:15 — outlet and stored state
class ViewController: UIViewController, ARSessionDelegate {
@IBOutlet var arView: ARView!
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Device capability check and session start | ViewController.viewDidAppear |
fatalError if ARBodyTrackingConfiguration.isSupported is false (BodyDetection/ViewController.swift:28) |
| Character loading | ViewController.viewDidAppear |
Started after the anchor is added to the scene |
| Pose following | ViewController.session(_:didUpdate:) |
Copies body-anchor position plus offset and rotation each update |
| Deferred attachment | ViewController.session(_:didUpdate:) |
Parents the character only when both the body anchor and the model exist |
| Scene configuration | AppDelegate, Info.plist |
Declarative scene manifest; no code builds the window |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Delegate or data-source callbacks | BodyDetection/ViewController.swift:24 assigns arView.session.delegate = self; callback at BodyDetection/ViewController.swift:59 |
ARKit pushes anchor updates into the controller that owns the scene graph |
Main application flow
Scope: the controller appears, starts body tracking, and attaches the character once both inputs are ready.
sequenceDiagram
participant VC as ViewController
participant Session as ARSession
participant Loader as EntityLoader
participant Anchor as AnchorEntity
VC->>Session: delegate = self, run(ARBodyTrackingConfiguration)
VC->>Loader: loadBodyTrackedAsync("character/robot")
Loader-->>VC: receiveValue sets character
Session-->>VC: session didUpdate anchors
VC->>Anchor: position and orientation from ARBodyAnchor
VC->>Anchor: addChild(character) when parent is nil
Reference code
BodyDetection/ViewController.swift:34 — viewDidAppear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
arView.session.delegate = self
// ...
let configuration = ARBodyTrackingConfiguration()
arView.session.run(configuration)
arView.scene.addAnchor(characterAnchor)
// ...
}BodyDetection/ViewController.swift:74 — session(_:didUpdate:)
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
for anchor in anchors {
guard let bodyAnchor = anchor as? ARBodyAnchor else { continue }
// ...
let bodyPosition = simd_make_float3(bodyAnchor.transform.columns.3)
characterAnchor.position = bodyPosition + characterOffset
// ...
characterAnchor.orientation = Transform(matrix: bodyAnchor.transform).rotation
// ...
if let character = character, character.parent == nil {
// ...
characterAnchor.addChild(character)
}
}
}Naming conventions
- Types: UIKit template names (
AppDelegate,SceneDelegate,ViewController). - Protocols: none declared locally.
- Methods: framework callback signatures only (
viewDidAppear,session(_:didUpdate:), scene lifecycle hooks). - Properties:
character…prefix groups the model, its offset, and its anchor.
Architecture takeaways
- Separate “where the body is” (an
AnchorEntityupdated every frame) from “what to draw” (a loadedBodyTrackedEntity), then join them once both exist. - A local
AnyCancellablecaptured by its own closures is a compact way to run a one-shot Combine load without a stored property. - A storyboard-backed scene manifest lets the app delegate stay a configuration stub.
- Body tracking needs a capability check before running the configuration.
Source map
| Source file | Relevant symbols |
|---|---|
BodyDetection/AppDelegate.swift |
AppDelegate, application(_:configurationForConnecting:options:) |
BodyDetection/SceneDelegate.swift |
SceneDelegate |
BodyDetection/ViewController.swift |
ViewController, viewDidAppear, session(_:didUpdate:) |
BodyDetection/Base.lproj/Main.storyboard |
initial ViewController, arView outlet |
BodyDetection/Info.plist |
UIApplicationSceneManifest |