Canvatorium Visio Lab 5020
Adding a Drag Gesture to an Entity.
Convert the coordinate space from the drag to 3D. Enable a full speed particle emitter while dragging.
struct Lab5020: View {
var dragGesture: some Gesture {
DragGesture()
// 1. targetedToAnyEntity will convert the gesture to one compatble with RealityKit
.targetedToAnyEntity()
.onChanged { value in
// 2. Get the location 3D from the gesture and convert it to 3D space for the entity
value.entity.position = value.convert(value.location3D, from: .global, to: value.entity.parent!)
// 3. Toggle our particle emitters to show fullSpeed while dragging
if let fullSpeed = value.entity.findEntity(named: "FullSpeed"), let cruisingSpeed = value.entity.findEntity(named: "CruisingSpeed") {
if(!fullSpeed.isEnabled) {
fullSpeed.isEnabled = true
}
if(cruisingSpeed.isEnabled) {
cruisingSpeed.isEnabled = false
}
}
}
.onEnded { value in
print(value.entity)
// 4. Toggle our particle emitters to the default state on end
if let fullSpeed = value.entity.findEntity(named: "FullSpeed"), let cruisingSpeed = value.entity.findEntity(named: "CruisingSpeed") {
fullSpeed.isEnabled = false
cruisingSpeed.isEnabled = true
}
}
}
var body: some View {
RealityView { content in
if let root = try? await Entity(named: "5019ScaleVolume", in: realityKitContentBundle) {
// Set up the tiny skybox
guard let resource = try? await TextureResource(named: "Starfield") else {
fatalError("Unable to load starfield texture.")
}
var material = UnlitMaterial()
material.color = .init(texture: .init(resource))
let skybox = Entity()
skybox.components.set(ModelComponent(
mesh: .generateSphere(radius: 5),
materials: [material]
))
skybox.scale *= .init(x: -1, y: 1, z: 1)
root.addChild(skybox, preservingWorldTransform: true)
// 5. Set the initial state
// Deactivating an entity in RCP seems to be different than isEnabled
if let fullSpeed = root.findEntity(named: "FullSpeed"), let cruisingSpeed = root.findEntity(named: "CruisingSpeed") {
fullSpeed.isEnabled = false
cruisingSpeed.isEnabled = true
}
root.scale = [0.2, 0.2, 0.2]
root.position = [0, -1, 0]
content.add(root)
}
}
.scaleEffect(x: 0.2, y: 0.2, z: 0.2)
// 6. Use the gesture
.gesture(dragGesture)
}
}