2

I'm trying to rotate the steel box given in the starter code for RealityKit, and I use this code

steelBox.transform.rotation += simd_quatf(angle: radians,
                                           axis: SIMD3<Float>(0, 1, 0)) 

to attempt to rotate the object.

When the object rotates, however, it grows bigger in one dimension as well.

Why is that?

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
Rach
  • 31
  • 1
  • 3

2 Answers2

3

Use a compound multiplication operator *= instead of a compound addition +=.

steelBox.transform.rotation *= simd_quatf(angle: .pi / 4,        // 45 degrees
                                           axis: SIMD3<Float>(0, 1, 0)) 

Let's see how your rotation looks like inside 4x4 matrix when you're using compound addition and multiplication.

You should print values of your matrix:

print((boxScene.steelBox?.transform.matrix)!)

Identity Matrix.

┌              ┐
|  1  0  0  0  |
|  0  1  0  0  |
|  0  0  1  0  |
|  0  0  0  1  |
└              ┘

Matrix storing results after Compound Addition (rotate 45 deg CCW around Y axis):

┌                      ┐
|  1.4   0    2.9   0  |
|  0     2    0     0  |
| -2.9   0    1.4   0  |
|  0     0    0     1  |
└                      ┘

Matrix storing results after Compound Multiplication (rotate 45 deg CCW around Y axis):

┌                      ┐
|  1.4   0    1.4   0  |
|  0     2    0     0  |
| -1.4   0    1.4   0  |
|  0     0    0     1  |
└                      ┘
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
2

If it's a quaternion rotation you are accumulating, you probably want to be using either:

steelBox.transform.rotation = 
   simd_mul(steelBox.transform.rotation, 
           simd_quatf(angle: radians,
                      axis: SIMD3<Float>(0, 1, 0)) )

or

steelBox.transform.rotation = 
   simd_mul(simd_quatf(angle: radians,
                       axis: SIMD3<Float>(0, 1, 0)),
            steelBox.transform.rotation )

depending on whether you want to 'add' the rotation in pre or post the initial orientation (I'm not sure which, because it depends on whether simd_mul does parent * child, or child * parent - the apple docs don't state which?).

quaternions follow the same rules as with transformation matrices. So if you are talking about 'adding' (accumulating) a rotation, you actually mean 'multiply'. Using the addition operator on a quaternion will impart a scaling operation.

robthebloke
  • 9,331
  • 9
  • 12