简体   繁体   中英

Chase camera in SceneKit

Say I have a node which is a cube and I am moving it within the scene, how can I have a camera that follows the box?

I understand there is SCNLookAtConstraint , but what I am after is a chase camera. One that actually changes it's position so that it is sort of attached behind the node.

I have not found any example code which shows a way of implementing this, does anyone have any ideas?

不能将相机节点设为Box节点的子节点吗?

Plenty of good ideas here already. :) Here's a third (and fourth?) option: in iOS 11 (and macOS 10.13, etc) there are a lot more SCNConstraint types available, so you can easily chain them together to achieve various styles of "chase camera" behavior.

You can see some more about this and a few examples in the WWDC17 talk on SceneKit :

  • SCNLookAtConstraint + SCNReplicatorConstraint gets you something like recent 3D Mario games, where the camera follows the player but its orientation relative to the world doesn't change.

  • SCNLookAtConstraint + SCNDistanceConstraint give you more of a "chase camera" style, where the camera turns with the player automatically.

Adding SCNAccelerationConstraint to either of those makes it feel more natural by smoothing out quick movements and gradually catching up to the player. You can also add in things like SCNAvoidOccluderConstraint for behaviors common to many third-person games where the camera won't go through a wall, will avoid trying to look through a column, etc.


Prior to iOS 11, you might use SCNTransformConstraint and a block that resets the camera node's position based on that of the moving cube. Combine that with a look-at constraint to keep the camera pointed at the cube, and tweak the influenceFactor of each constraint for the degree of smoothing/lag you want.

There is an example similar to this in the SceneKit Vehicle sample code. The SCNCamera follows the car with some delay. Look here .

It works by computing the position of where the camera should be based on the position of the vehicle. And then it interpolates the current camera position to the destination position.

I much prefer Rickster's approach over anything else suggested.

Making the camera node a child of the box node would work but if the box was rotated, the camera would be pointing at an awkward angle.

A much cleaner way:

let distanceConstraint             = SCNDistanceConstraint(target: box)
distanceConstraint.minimumDistance = 55
distanceConstraint.maximumDistance = 60

let lookAtConstraint                 = SCNLookAtConstraint(target: box)
lookAtConstraint.isGimbalLockEnabled = true
cameraNode.constraints               = [lookAtConstraint,distanceConstraint]
scnView.scene?.rootNode.addChildNode(cameraNode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM