I'm trying to add buttons to my immersive view. The buttons have been added perfectly, but when I click on them, nothing happens. The click event is not being recognized at all.
Here's my implementation
struct ImmersiveView: View {
// ... other properties
@State private var opacity: Double = 1.0
@State private var hotspots: [Hotspot] = []
@State private var selectedHotspot: Hotspot?
@State private var isTransitioning = false
var body: some View {
ZStack {
RealityView { content in
// Load immersive content
} update: { content in
// Update immersive content
}
.opacity(opacity)
// Interactive hotspots
ForEach(hotspots, id: \.id) { hotspot in
createHotspotEntity(hotspot: hotspot) // Function to create hotspots
}
}
.task {
await loadTextureForCurrentImage() // Loading images
}
.gesture(
SpatialTapGesture()
.targetedToAnyEntity()
.onEnded { value in
handleTap(value) // Handling tap gesture
}
)
}
private func createHotspotEntity(hotspot: Hotspot) -> ModelEntity {
let hotspotEntity = ModelEntity()
let hudYellow = UIColor(red: 1.0, green: 0.8, blue: 0.0, alpha: 1.0)
let radius: Float = 1.5
let sphereMesh = MeshResource.generateSphere(radius: radius)
var material = UnlitMaterial()
material.color = .init(tint: hudYellow.withAlphaComponent(0.8))
let sphereEntity = ModelEntity(mesh: sphereMesh,
materials: [material],
collisionShape: .generateSphere(radius: radius),
mass: 0.0)
hotspotEntity.addChild(sphereEntity)
let worldRadius: Float = 85
let phi = Float.pi / 2 - hotspot.position.y
let theta = hotspot.position.x
let x = worldRadius * sin(phi) * cos(theta)
let y = worldRadius * cos(phi)
let z = worldRadius * sin(phi) * sin(theta)
hotspotEntity.position = [x, y, z]
hotspotEntity.look(at: [0, 0, 0], from: hotspotEntity.position, relativeTo: nil)
hotspotEntity.name = "Hotspot_\(hotspot.id)"
hotspotEntity.components[DestinationComponent.self] = DestinationComponent(destinationId: hotspot.destinationImageId ?? "", label: hotspot.label)
hotspotEntity.components[HotspotComponent.self] = HotspotComponent()
// Add components for interaction
hotspotEntity.components.set(InputTargetComponent(allowedInputTypes: .indirect))
hotspotEntity.components.set(CollisionComponent(shapes: [.generateSphere(radius: radius)], mode: .trigger, filter: .sensor))
return hotspotEntity
}
private func handleTap(_ value: EntityTargetValue<SpatialTapGesture.Value>) {
print("Handling tap on entity: \(value.entity.name)")
if let destinationComponent = value.entity.components[DestinationComponent.self] {
let destinationId = destinationComponent.destinationId
print("Hotspot tapped. Destination ID: \(destinationId)")
transitionToNextImage(destinationId: destinationId)
} else {
print("Tapped entity does not have a DestinationComponent")
}
}
private func transitionToNextImage(destinationId: String) {
guard !isTransitioning else { return }
// Transition logic
}
}