问题
I am trying to implement some code based on an ARKit demo where someone used this helper function to place a waypoint
let rotationMatrix = MatrixHelper.rotateAboutY(
degrees: bearing * -1
)
How can I implement the .rotateAboutY function using the SIMD library and not using GLKit? To make it easier, I could start from the origin point.
I'm not too handy with the matrix math so a more basic explanation would be helpful.
回答1:
The rotation around Y matrix is:
| cos(angle) 0 sin(angle)|
| 0 1 0 |
|-sin(angle) 0 cos(angle)|
Rotation counter-clockwise around Y:
|cos(angle) 0 -sin(angle)|
| 0 1 0 |
|sin(angle) 0 cos(angle)|
So, we can easily construct the matrix using simd (Accelerate Framework):
func makeRotationYMatrix(angle: Float) -> simd_float3x3 {
let rows = [
simd_float3(cos(angle), 0, -sin(angle)),
simd_float3(0, 1, 0),
simd_float3(-sin(angle), 0, cos(angle))
]
return float3x3(rows: rows)
}
The angle here is in radians. More info here.
回答2:
Probably the best way to leverage the built-in SIMD library for such operations (at least, with "best" meaning "do the least math yourself") is to express rotations with quaternions and convert to matrices when needed.
- Construct a
simd_quatf
representing the axis-angle rotation you want to apply. - Convert that quaternion to a 4x4 matrix.
You can do that with a one-line call :
let rotationMatrix = float4x4(simd_quatf(angle: radians, axis: axis))
Expanding to your "rotateAboutY" case:
let radians = degreesToRadians(-bearing) // degrees * .pi / 180
let yAxis = float3(0, 1, 0)
let rotationMatrix = float4x4(simd_quatf(angle: radians, axis: yAxis))
Of course, once you have a rotation matrix, you can apply it using the *
or *=
operator:
someNode.simdTransform *= rotationMatrix
If you find yourself doing something like this often, you might want to write an extension on float4x4
.
Tip: By the way, in Swift (or C++ or Metal shader language) you don't need the
simd_
prefix on most (but not all) SIMD types and global functions.
来源:https://stackoverflow.com/questions/45463627/how-do-i-rotate-an-arkit-4x4-matrix-around-y-using-apples-simd-library