F4Ke
F4Ke

Reputation: 1751

RealityKit – Detect when finished moving an entity

Using RealityKit's installGestures for an entity, I am able to move, rotate and resize them. And that's cool, But I would like to be able to detect when the user finished to move the object in order to trigger something.

For now I have this:

guard let entity = try? ModelEntity.loadModel(named: "\(name).usdz") 
else {
    NSLog("ERROR loading model")
    return
}
entity.generateCollisionShapes(recursive: true)

arView.installGestures(.all, for: entity)
    
let anchorEntity = AnchorEntity(world: position)
    
anchorEntity.addChild(entity)
    
arView.scene.anchors.append(anchorEntity)

So now, How can I handle the gesture event in order to get the new position of the moved / resize oenetity?

Thanks !

Upvotes: 1

Views: 1248

Answers (1)

MasDennis
MasDennis

Reputation: 746

installGestures() actually returns an array with EntityGestureRecognizer instances. You can loop through this array and add a target to each recognizer:

arView.installGestures(.all, for: entity).forEach { gestureRecognizer in
    gestureRecognizer.addTarget(self, action: #selector(handleGesture(_:)))
}

Then you can add a gesture handler that checks for the appropriate gesture recognizer, inspects its .state property and acts accordingly:

@objc private func handleGesture(_ recognizer: UIGestureRecognizer) {
    guard let translationGesture = recognizer as? EntityTranslationGestureRecognizer else { return }
    
    switch translationGesture.state {
    case .began:
        print("Translation gesture began")
    case .ended:
        print("Translation gesture ended")
        // get entity.transform 
    default:
        break
    }
}

Upvotes: 4

Related Questions