Alessandro
Alessandro

Reputation: 4110

Apply a current running SCNAction to another SCNNode

I two SCNNodes A and B in my 3D world. A is moved by the user, while B has an action that makes it move from left to right. This is the action on B:

let moveDirection: Float = position.x > 0.0 ? -1.0 : 1.0
let moveDistance = levelData.gameLevelWidth()
let moveAction = SCNAction.moveBy(SCNVector3(x: moveDistance * moveDirection, y: 0.0, z: 0.0), duration: 10.0)
let action = SCNAction.runBlock { node -> Void in
}
carNode.runAction(SCNAction.sequence([moveAction, action]))

A and B can collide, and if a touches B, then A has to start moving with B as if they were one single object, until the user uses the commands to move A. The collision is detected in the method

func physicsWorld(world: SCNPhysicsWorld, didBeginContact contact: SCNPhysicsContact)

but I have no idea what approach I should take to make A move with B. I was thinking to apply a copy of the action with new positions, or if possible, apply the currently executing action to node A. I also thought of making A a child of B and then moving it back to the root node, but it doesn't seem to work.

Upvotes: 0

Views: 510

Answers (1)

Alessandro
Alessandro

Reputation: 4110

The solution was simply accessing the current running SCNAnimations on the node that was involved in the collision with this code:

let action: SCNAction = contact.nodeB.actionForKey("MovementAction")!
contact.nodeA.runAction(action)

Once you have a reference to the current action, you can just run it on the other node, and it will be mirrored exactly.

note: remember to specify the key for the action when you create it, otherwise this method won't work.

Upvotes: 1

Related Questions