iosswiftscenekitscnnode

Animating SCNConstraint (LookAt) for SCNNode in SceneKit game to make the transition gradual


In general, when one wants to make a character in a game face the camera, one can use SCNLookAtConstraint, which actually is serving me well too.

Below, my_object is the node which I am trying to orient as per constraint. 'Enemy' refers to some node in the scene, and pointOfView is scene's point of View. When I tap on my_object it should look at enemy for a brief second, then back to my pointOfView.

Setting LookAtConstraint so that the 'object' looks at the 'enemy' for a second.

my_object.constraints?.removeAll()
let targetNode = sceneView.scene.rootNode.childNode(withName: (chosenScenarioForChallenge?.shape)!, recursively: true)
let lookAt = SCNLookAtConstraint(target: targetNode)
lookAt.isGimbalLockEnabled = true
my_object.constraints = [lookAt]                    
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(resetObject), userInfo: nil, repeats: false)

Resetting object to look at my point of view after a look at the 'enemy' node

@objc
func resetObject() {
    my_object.constraints?.removeAll()
    let targetNode = sceneView.pointOfView
    let lookAt = SCNLookAtConstraint(target: targetNode)
    lookAt.isGimbalLockEnabled = true
    my_object.constraints = [lookAt]
    }

My question is, I don't want the change in constraints to be abrupt. I want it to be smooth and hence I want to incorporate Animation in this. After looking at both SCNAction and SCNAnimation, I have failed to find anything related to constraints. As constraints update the position dynamically, I can understand SCNAction.move(to/ by: ) etc. won't work. Ultimately, when I tap, my object should start looking at the enemy node gradually and after 1-2 seconds goes by, it should come back to look at my pointOfView, that too gradually.

Please note that I don't want the character to look into camera technically, hence I am using SCNLookAtConstraint, rather than SCNBillboardConstraint.

Pointers would be helpful, TIA.


Solution

  • the target property is read-write so you should be able to reuse the SCNLookAtConstraint instance (instead of creating a new one) and just swap the target.

    Edit

    The influenceFactor of a constraint allows for a smoother animation between the node's current transform and the one computed by the constraint.