How do I rotate an object around only one axis in RealityKit?
In RealityKit there are, at least, three ways to rotate an object around single axis.
In each example we rotate an object counterclockwise (CCW).
First approach
let boxScene = try! Experience.loadBox()
boxScene.steelBox?.orientation = simd_quatf(angle: .pi/4, /* 45 Degrees */
axis: [0,0,1]) /* About Z axis */
Second approach
boxScene.steelBox?.transform = Transform(pitch: 0,
yaw: 0,
roll: .pi/4) /* Around Z axis */
pitch, yaw and roll are rotations about X, Y and Z axis expressed in radians.
Third approach
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)
Visual representation of 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.
RealityKit – Can't rotate object properly
Use *=
compound multiply operator instead of +=
compound addition.
Here is the explanation.
Change a rotation of AnchorEntity in RealityKit
Try move(...)
instance method:
import UIKit
import RealityKit
import SceneKit
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
let box = try! Experience.loadBox()
let entity = box.steelBox!
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
let currentMatrix = entity.transform.matrix
// Nothing prevents you from using even SceneKit's matrix methods
let rotation = simd_float4x4(SCNMatrix4MakeRotation(.pi/2, 0,1,0))
let transform = simd_mul(currentMatrix, rotation)
entity.move(to: transform, relativeTo: nil, duration: 3.0)
}
arView.scene.anchors.append(box)
}
}
Related Topics
Saving Nsimage in Different Formats Locally
Swift. Combine. How to Call a Publisher Block More Than Once When Retry
Swift 4.2 - _Shared Attribute Near Type
Storing Array of Custom Objects in Userdefaults
How to "Explicitly" Implement a Protocol in Swift? If It Is Impossible, Why
Initializing Property via Closure
In Swift, How to Wait Until a Server Response Is Received Before I Proceed
Cannot Call Value of Non-Function Type 'Nshttpurlresponse' Alamofire Objectmapper
Why Is Uint64 Max Equal -1 in Swift
Get the String Up to a Specific Character
Set a Variable to the < ("Less Than") Operator as a Function in Swift
How to Create a Circle with Rounded Ends for Each Quadrant
Capturing a Struct Reference in a Closure Doesn't Allow Mutations to Occur
Swiftui - Make Toolbar's Navigationlink Use Detail View
How, Exactly, Do I Render Metal on a Background Thread
Why Do We Need to Set Delegate to Self? Why Isn't It Defaulted by the Compiler