Contact
Events associated with collisions.
Declaration
struct ContactOverview
To subscribe to a collision event, import Combine, create a property of type Cancellable so that you maintain a reference to the subscription, then call subscribe(to:on:_:) or subscribe(to:on:componentType:_:) and provide a closure.
The closure is passed an RealityKit/Scene/Event object that contains information relevant to the type of event you subscribed to.
Here’s an example of subscribing to the collision begain event and retrieving the two entities involved in the collision:
import AppKit
import RealityKit
import Combine
class GameViewController: NSViewController {
@IBOutlet var arView: ARView!
var collisionSubscription:Cancellable?
override func awakeFromNib() {
let boxAnchor = try! Experience.loadBox()
arView.scene.anchors.append(boxAnchor)
collisionSubscription = arView.scene.subscribe(
to: CollisionEvents.Began.self,
on: boxAnchor
) { event in
print("collision started")
let firstEntity = event.entityA
let secondEntity = event.entityB
// Take appropriate action...
}
}
}You can also create a function to respond to the event rather than a closure by using sink(receiveCompletion:receiveValue:). Here’s an example of using a function to respond to a collision event:
import AppKit
import RealityKit
import Combine
class GameViewController: NSViewController {
@IBOutlet var arView: ARView!
var collisionSubscription:Cancellable?
override func awakeFromNib() {
let boxAnchor = try! Experience.loadBox()
arView.scene.anchors.append(boxAnchor)
collisionSubscription = arView.scene.publisher(for: CollisionEvents.Began.self,
on:nil).sink(receiveValue: onCollisionBegan)
}
private func onCollisionBegan(_ event:
CollisionEvents.Began) {
print("collision started")
let firstEntity = event.entityA
let secondEntity = event.entityB
// Take appropriate action...
}
}