【问题标题】:How to move a SCNNode in the direction it is pointing at after an rotation is applied如何在应用旋转后沿其指向的方向移动 SCNNode
【发布时间】:2017-06-18 12:18:41
【问题描述】:

我的困境是: 我有一艘宇宙飞船,位于恒星和行星之间的太空中。相机被添加为 spaceshipNode 的子节点,并且您始终注视着飞船的背面(在上方升高了几个单位)。 我使用 CoreMotion 像这样旋转宇宙飞船:

    func startMonitoringMotion() {
    self.motionManager?.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: { (data, error) in
        guard let data = data else { return }

        let attitude: CMAttitude = data.attitude
        self.ship.eulerAngles = SCNVector3Make(Float(attitude.roll - M_PI_2), Float(attitude.yaw), Float(attitude.pitch))
    })
}

并且旋转按预期工作。

现在我想将飞船朝它所面对的方向移动,但我不知道该怎么做。我尝试了不同的方法,但都失败了。

我已经无数次搜索了这个论坛好几天,但没有运气。 我希望有人可以为我(和我的飞船)指明正确的方向。

提前谢谢你。

【问题讨论】:

    标签: rotation swift3 scenekit trigonometry


    【解决方案1】:

    我发现最简单的方法是获取节点worldTransform 属性的第三行,该属性对应于它的 z 轴。

    func getZForward(node: SCNNode) -> SCNVector3 {
        return SCNVector3(node.worldTransform.m31, node.worldTransform.m32, node.worldTransform.m33)
    }
    
    ship.position += getZForward(ship) * speed // nb scalar multiply requires overload of * func
    // if node has a physics body, you might need to use the presentationNode, eg:
    // getZForward(ship.presentationNode)
    // though you probably don't want to be directly modifying the position of a node with a physics body
    

    在这里查看讨论Getting direction that SCNNode is facing

    iOS 11 更新

    iOS 11 为获取节点的方向添加了方便的便利功能。在这种情况下,worldForward 属性就是您想要的。此外,SCNNode 上所有返回 SCNVector 和矩阵类型的属性现在都有返回 simd 类型的版本。因为 simd 已经为算术运算符提供了重载,所以您不再需要为 SCNVectorSCNMatrix 类型添加算术覆盖集。

    所以我们可以去掉上面的 getZForward 方法,只需要一行:

    ship.simdPosition += ship.simdWorldFront * speed
    

    【讨论】:

    • 您好,非常感谢您的意见。几天前,我发现您在讨论中提出了相同的解决方案,我一直在努力结合 CoreMotion 来控制船。我想等待将您的答案标记为“答案”,直到我确定这对我来说是正确的解决方案......现在我认为它是,非常感谢你。
    • @Sanxion 你能发布你的 CoreMotion 解决方案吗?
    • 是的 SIMD 和简单的访问器!
    • @OliverD - 非常感谢您花时间更新您的答案。我最终为该项目抽出时间,但我现在会根据您的新信息再次尝试。
    • @user287474 - 您好,很抱歉我之前没有看到您的问题。我最终从我的宇宙飞船项目中抽离了一些时间,但我会再次开始工作。一旦我再次找到可行的解决方案,我将发布相关代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2023-04-05
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多