如何在 RealityKit 中仅围绕一个轴旋转对象?

How do I rotate an object around only one axis in RealityKit?

我正在尝试围绕其 z 轴旋转立方体,但找不到方法。

RealityKit 中有没有办法做到这一点?

对于也在搜索此内容的人,您需要使用 transformrotation。 这需要一个 simd_quatf ,您可以在其中给出 angleaxis.

在我的例子中,我不得不使用这个:

"object".transform.rotation = simd_quatf(angle: GLKMathDegreesToRadians(90), axis: SIMD3(x: 0, y: 0, z: 1))

在RealityKit中,至少有3种绕单轴旋转对象的方法

在每个示例中,我们逆时针 (CCW) 旋转对象。


第一种方法

let boxScene = try! Experience.loadBox()

boxScene.steelBox?.orientation = simd_quatf(angle: .pi/4,    /* 45 Degrees */
                                             axis: [0,0,1])  /* About Z axis */


第二种方法

boxScene.steelBox?.transform = Transform(pitch: 0, 
                                           yaw: 0, 
                                          roll: .pi/4)      /* Around Z axis */

pitchyawroll是绕X、Y、Z轴的旋转表示以弧度为单位。


第三种方法

let a: Float = cos(.pi/4)
let b: Float = sin(.pi/4)

let matrix = float4x4([ a, b, 0, 0 ],        /* column 0 */
                      [-b, a, 0, 0 ],        /* column 1 */
                      [ 0, 0, 1, 0 ],        /* column 2 */
                      [ 0, 0, 0, 1 ])        /* column 3 */

boxAnchor.steelBox?.setTransformMatrix(matrix, relativeTo: nil)

旋转矩阵的视觉表示如下所示:

let a: Float = cos(.pi/4)
let b: Float = sin(.pi/4)

//  0  1  2  3
 ┌              ┐
 |  a -b  0  0  |
 |  b  a  0  0  |
 |  0  0  1  0  |
 |  0  0  0  1  |
 └              ┘

如果您想了解更多关于旋转矩阵的信息,请阅读 this post。