ios - 如何更改对象 Swift SceneKit 的位置

标签 ios swift scenekit

我在一个 SceneKit 中有两个对象。一个是地球,另一个是月球。它们都位于 x:0、y:0、z:0 并且重叠。我应该如何改变月球的坐标使其绕地球转?

这里是代码:

import UIKit
import SceneKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = SCNScene()

        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()

        cameraNode.position = SCNVector3(x:0, y:0, z:10)

        scene.rootNode.addChildNode(cameraNode)

        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light?.type = .directional
        lightNode.position = SCNVector3(x:0, y:0, z:2)

        scene.rootNode.addChildNode(lightNode)

        let stars = SCNParticleSystem(named: "StarsParticles.scnp", inDirectory: nil)!
        scene.rootNode.addParticleSystem(stars)

        let moonNode = MoonNode()
        scene.rootNode.addChildNode(moonNode)

        let sceneview = self.view as! SCNView
        sceneview.scene = scene

        let earthNode = EarthNode()
        scene.rootNode.addChildNode(earthNode)

        let sceneView = self.view as! SCNView
        sceneView.scene = scene

        sceneView.showsStatistics = false
        sceneView.backgroundColor = UIColor.black
        sceneView.allowsCameraControl = true
    }

    override var prefersStatusBarHidden: Bool {
        return true 
    }
}

最佳答案

你可以让你的 View Controller 成为一个SCNSceneRendererDelegate,并实现委托(delegate)方法renderer:willRenderScene,它给你一个时间。基于那个时间,你可以这样设置:

moonNode.position = SCNVector3(r * cos(Float(time), r * sin(Float(time)), 0)

其中 r 是地球节点的半径 - 如果您在编译时不知道这一点,只需在该行上方包含如下内容:

let r = length(float3(earthNode.boundingBox.max) - float3(earthNode.boundingBox.min))

这对于我包含的导致 xy 平面旋转的代码来说并不十分准确,但它至少会为您提供 r 的正确数量级。如果您遇到找不到 float3 或长度的错误,请尝试 import simd

如果您对此有任何疑问,请告诉我,因为这是我凭内存输入的。

文档中的更多信息:https://developer.apple.com/documentation/scenekit/scnscenerendererdelegate/1523483-renderer

关于ios - 如何更改对象 Swift SceneKit 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52246723/

相关文章:

ios - 隐藏 SCNFloor 但使用 SceneKit 显示阴影(快速)

c# - 您如何才能在 Xamarin.iOS UITableView 上仅圆化 2 个角?

ios - 调用 didEnterBackground 后是否可以在主线程上执行某些操作?

ios - 使用 Swift + FMDB 打开和关闭数据库

ios - '@lvalue $T 7' is not identical to ' CGPoint!'

swift - 如何使用 Xcode 转换器创建 USDZ 文件?

ios - 尝试在重新排序已经在进行时开始对 Collection View 重新排序

ios - '尝试使用 deleteCharactersInRange 改变不可变对象(immutable对象)' : Xcode 7. 2 创建存档以上传到应用商店时出错

iOS 旋转中心按钮

ios - Swift 2 - iOS - 分派(dispatch)回原始线程