如何在应用旋转后沿它指向的方向移动 SCNNode
How to move a SCNNode in the direction it is pointing at after an rotation is applied
我的困境是:
我有一艘 space 飞船,位于恒星和行星之间的 space 某处。相机被添加为 spaceshipNode 的子节点,您始终会看到 spaceship 的背面(高出几个单位)。
我使用 CoreMotion 像这样旋转 spaceship:
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))
})
}
并且旋转按预期工作。
现在我想将 space飞船朝它所面对的方向移动,但我不知道该怎么做。我尝试过不同的方法,但都失败了。
几天来我在这个论坛上搜索了无数次,但没有找到。
我希望有人能给我(和我的 space飞船)指明正确的方向。
提前致谢。
我发现最简单的方法是获取节点 worldTransform
属性 的第三行,它对应于它的 z-forward 轴。
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
return SCNVector
和矩阵类型的所有属性现在都有 return simd 类型的版本。因为 simd 已经有算术运算符的重载,所以您不再需要为 SCNVector
和 SCNMatrix
类型添加算术覆盖集。
所以我们可以去掉上面的 getZForward
方法,只需要一行:
ship.simdPosition += ship.simdWorldFront * speed
我的困境是: 我有一艘 space 飞船,位于恒星和行星之间的 space 某处。相机被添加为 spaceshipNode 的子节点,您始终会看到 spaceship 的背面(高出几个单位)。 我使用 CoreMotion 像这样旋转 spaceship:
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))
})
}
并且旋转按预期工作。
现在我想将 space飞船朝它所面对的方向移动,但我不知道该怎么做。我尝试过不同的方法,但都失败了。
几天来我在这个论坛上搜索了无数次,但没有找到。 我希望有人能给我(和我的 space飞船)指明正确的方向。
提前致谢。
我发现最简单的方法是获取节点 worldTransform
属性 的第三行,它对应于它的 z-forward 轴。
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
return SCNVector
和矩阵类型的所有属性现在都有 return simd 类型的版本。因为 simd 已经有算术运算符的重载,所以您不再需要为 SCNVector
和 SCNMatrix
类型添加算术覆盖集。
所以我们可以去掉上面的 getZForward
方法,只需要一行:
ship.simdPosition += ship.simdWorldFront * speed