[英]SceneKit - adding SCNNode on another SCNNode
我试图将球体放在盒子顶部,但位置很奇怪:球被隐藏在盒子里面。 我试图改变盒子和球体枢轴,但它没有帮助。 这是代码:
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)`
我做错了什么? 如何将球放在盒子的顶部?
更新 :如果我添加Cube而不是球,它看起来很好,因为我想要
您需要在cube-height/2 + sphere-radius
的Y轴上进行平移。 因此你应该:
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的球的下半部分仍然在立方体内部。 您可以在编辑器中添加如下面场景中的立方体和球体,这应该有助于澄清。
一切都正常运行。 您将球节点添加到多维数据集节点。 因此,球节点的原点位于立方体的中心。 然后将球的位置更改为y轴上立方体大小的一半。 所以基本上它弹出,你只看到球的一半(半径为1)。
所以你必须再添加一半大小的球才能将它放在立方体的顶部:
ballNode.position = SCNVector3Make(0, 5.5, 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.