How do you attach an object to your camera position with ARKit Swift?

北战南征 提交于 2020-05-09 18:55:05

问题


I have moving objects which I want to have be able to collide with me the player. I have the ability to launch objects from me by getting my current position/direction at that time, but I do not understand how to attach an object to me which will follow my positioning at all times.


回答1:


In SceneKit, everything that can have a position in the scene is (attached to) a node. That includes not just visible objects, but also light sources and cameras. When you use ARSCNView, there's still a SceneKit camera, but ARKit controls its position/orientation.

SceneKit nodes create a hierarchy: every node's position (and orientation etc) are relative to its parent node. If the parent node moves within the scene, its children move along with it so that they keep the same parent-relative positions. So, if you want something to always keep the same position relative to the camera, you should make that content a child of the camera node.

Even in scenes where you don't create a camera yourself — such as when SceneKit and ARKit manage the camera for you — you can get the node containing the current camera with the view's pointOfView property. (Note: ARSCNView is a subclass of SCNView, most of whose useful API is defined by the SCNSceneRenderer protocol.)

You may have to wait until the session starts running to access the ARKit-managed camera node.




回答2:


ARSCNView has a property 'pointOfView'. You can attach a child node to it.

let ball = SCNSphere(radius: 0.02)
ballNode = SCNNode(geometry: ball)
ballNode?.position = SCNVector3Make(0, 0, -0.2)
sceneView.pointOfView?.addChildNode(ballNode!)

The node will follow your camera anywhere you go.




回答3:


Following code work for me to get the current position(x,y,z coordinates) of the camera.

    let pov = sceneView.pointOfView
    let position = pov?.position

    let x = position?.x
    let y = position?.y
    let z = position?.z



回答4:


You need to take Jimi's answer and give the ball a color or texture to see it:

let ball = SCNSphere(radius: 0.02)
ball.firstMaterial?.diffuse.contents = UIColor.red
let ballNode = SCNNode(geometry: ball)
ballNode.position = SCNVector3Make(0, 0, -0.2)
self.sceneView.pointOfView?.addChildNode(ballNode)


来源:https://stackoverflow.com/questions/44531963/how-do-you-attach-an-object-to-your-camera-position-with-arkit-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!