SceneKit - 在另一个 SCNNode 上添加 SCNNode [英] SceneKit - adding SCNNode on another SCNNode
问题描述
我试图将球体放在盒子的顶部,但位置很奇怪:球半隐藏在盒子里.我尝试更改框和球体枢轴,但没有帮助.代码如下:
I'm trying to put sphere on top of the box, but the position is strange: Ball is half hidden inside box. I tried to change box and sphere pivot, but it didn't help. Here's the code:
let cubeGeometry = SCNBox(width: 10, height: 10, length: 10,
chamferRadius: 0)
let cubeNode = SCNNode(geometry: cubeGeometry)
//cubeNode.pivot = SCNMatrix4MakeTranslation(0, 1, 0)
scene.rootNode.addChildNode(cubeNode)
let ballGeometry = SCNSphere(radius: 1)
let ballNode = SCNNode(geometry: ballGeometry)
ballNode.pivot = SCNMatrix4MakeTranslation(0.5, 0, 0.5)
ballNode.position = SCNVector3Make(0, 5, 0)
cubeNode.addChildNode(ballNode)`
结果:
我做错了什么?如何将球放在盒子的正上方?
what I'm doing wrong? How to put the ball right on the top side of the box?
更新:如果我添加立方体而不是球,它看起来不错
UPDATE: If I add Cube instead of ball, it looks good as I want
推荐答案
您需要通过 cube-height/2 + sphere-radius
在 Y 轴上平移.因此你应该有:
You need to translate on the Y-axis by cube-height/2 + sphere-radius
. Thus you should have:
ballNode.position = SCNVector3Make(0, 6, 0)
截图如下:
相关完整代码:
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = SCNScene()
let cubeGeometry = SCNBox(width: 10, height: 10, length: 10,
chamferRadius: 0)
cubeGeometry.firstMaterial?.diffuse.contents = UIColor.yellow
let cubeNode = SCNNode(geometry: cubeGeometry)
scene.rootNode.addChildNode(cubeNode)
let ballGeometry = SCNSphere(radius: 1)
ballGeometry.firstMaterial?.diffuse.contents = UIColor.green
let ballNode = SCNNode(geometry: ballGeometry)
ballNode.position = SCNVector3Make(0, 6, 0)
cubeNode.addChildNode(ballNode)
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.gray
}
更新:为什么是半径而不是半径/2
在 Xcode 中的场景编辑器中查看此屏幕截图.立方体的原始位置是 (0, 0, 0) 球的位置也是如此;因此球需要移动 r 而不是 r/2;对于 r/2,高度为 r/2 的球的下部将仍在立方体内.您可以在编辑器中添加一个立方体和球体,如下面的场景所示,这应该有助于澄清.
See this screenshot from the Scene Editor in Xcode. The original position of cube is (0, 0, 0) and so is that of the ball; hence the ball needs to be moved by r and not r / 2; with r / 2 the lower section of the ball with height r/2 will be still inside the cube. You can just add a cube and sphere as in the scene below in the editor and that should help clarify.
这篇关于SceneKit - 在另一个 SCNNode 上添加 SCNNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!