Hi @sarangb
Your approach to targeting a gesture to entities with a specific component looks correct to me, but since I can't see how/where you are creating the entities with the component it's a bit difficult for me to help you figure out what's going wrong. Could you show me how you are creating the entities with the ToyComponent
?
Otherwise, here's an example that demonstrates how to use targetedToEntity(where:)
to target a drag gesture to only the entities with a specific component.
struct ToyComponent: Component {
}
struct ImmersiveView: View {
// Creates a sphere with a collision component and an input target component
// that can be the target of drag gestures.
func createDraggableSphere(color: SimpleMaterial.Color) -> Entity {
let entity = ModelEntity(mesh: .generateSphere(radius: 0.05), materials: [SimpleMaterial(color: color, isMetallic: false)])
entity.generateCollisionShapes(recursive: false)
entity.components.set(InputTargetComponent())
return entity
}
var body: some View {
RealityView { content in
// Create two draggable spheres that both have a `ToyComponent`.
let toyEntity1 = createDraggableSphere(color: .green)
toyEntity1.components.set(ToyComponent())
toyEntity1.position = [-0.25, 1, -1]
content.add(toyEntity1)
let toyEntity2 = createDraggableSphere(color: .green)
toyEntity2.components.set(ToyComponent())
toyEntity2.position = [0, 1, -1]
content.add(toyEntity2)
// Create one draggable sphere without a `ToyComponent`.
let nonToyEntity = createDraggableSphere(color: .red)
nonToyEntity.position = [0.25, 1, -1]
content.add(nonToyEntity)
}
.gesture(
DragGesture()
.targetedToEntity(where: .has(ToyComponent.self))
.onChanged({ value in
value.entity.position = value.convert(value.location3D, from: .local, to: value.entity.parent!)
})
)
}
}
This snippet creates three spheres with collision and input target components that can be the target of a drag gesture. Two of the spheres have ToyComponent
s (the green spheres) and one of the spheres does not (the red sphere). The drag gesture should only be able to target the two green spheres with the ToyComponent
s.
Let me know if you continue to run into any issues!