Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scenekit object that stays in the center of the camera view (Swift)

So I have a camera in my SceneKit project that is able to rotate and move around freely, and I have an object that, in some cases, needs to stay at a constant distance away from the camera and always be in the center of its view no matter how the camera rotates. Unfortunately, I'm new to SceneKit and don't know how to accomplish this.

So the key things I'm looking for are:

  1. How to have the object always at the same distance from the camera

  2. How to have the object always be in the center of the camera's view no matter what direction it's looking

At the moment, both the camera and the object (an SCNNode with a box geometry) are children of the same scene.

I'm coding in swift so I'd prefer an answer using that, but if you have a solution in objective-c, that works too.

Thanks a bunch!

like image 243
Armin Avatar asked Oct 18 '22 09:10

Armin


1 Answers

Think about how you might solve this in the real world. Grab a two by four of the appropriate length. Use duct tape to attach the ball to one end, and to attach the camera (aimed at the ball) to the other end.

Now you can carry that rig around with you. The ball will always be in the center of the camera view, and will be a constant distance away from the camera.

You can build the same rig, virtually, in SceneKit. Create a new SCNNode to be the rig (taking the place of the two by four). Add the ball as a child node, at (0, 0, 0). Add the camera as a child node too, at (0, 0, 5) (camera looks down the -Z axis, so this position should put the ball in the center of the view). Now you can move the rig node anywhere in the scene you want, and you'll have a consistent ball position.

like image 155
Hal Mueller Avatar answered Oct 27 '22 21:10

Hal Mueller