I'm trying to rotate a cube around its z-axis but I can't find how.
Is there a way in RealityKit to do this?
I'm trying to rotate a cube around its z-axis but I can't find how.
Is there a way in RealityKit to do this?
In RealityKit there are, at least, three ways to rotate an object around single axis.
In each example we rotate an object counterclockwise (CCW).
Use simd_quatf
initializer that has angle (it's expressed in radians) and axis parameters:
let scene = try! Experience.loadBox()
scene.steelBox?.orientation = simd_quatf(angle: .pi/4, /* 45 Degrees */
axis: [0,0,1]) /* About Z axis */
Use Transform's pitch, yaw and roll that are rotations about X, Y and Z axis expressed in radians.
scene.steelBox?.transform = Transform(pitch: 0,
yaw: 0,
roll: .pi/4) /* Around Z axis */
Use float4x4
initializer, representing each column with 4 slots horizontally:
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 */
scene.steelBox?.setTransformMatrix(matrix, relativeTo: nil)
Real-world visual representation of 4x4 rotation matrix looks like this:
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 |
└ ┘
If you wanna know more about Rotation Matrices, read this post.
Read this post, to find out how to overcome the 180 degree rotation barrier.
For people who are also searching for this you need to use transform and rotation. This needs a simd_quatf where you give the angle and the axis.
In my case i had to use this:
"object".transform.rotation = simd_quatf(angle: GLKMathDegreesToRadians(90), axis: SIMD3(x: 0, y: 0, z: 1))