Search code examples
swiftswiftuirealitykit

Change a rotation of AnchorEntity in RealityKit


I placed 3d object to ARViewController after 3 seconds of placing object, then I want to rotate object by 90 degrees:

arView.scene.addAnchor(anchorEntity)

DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {

    print("after 3 sec ! ")
            
    let radians = 90.0 * Float.pi / 180.0
    
    anchorEntity.orientation = simd_quatf(angle: radians, 
                                           axis: SIMD3(x: 0, y: 1, z: 0))
}

It works very well but the problem is that I want to smooth rotation , as you can see short video, it suddenly rotate which seem weird.

How can I do this?

https://youtu.be/Ixk2elm-bfU


Solution

  • Try move(...) instance method immediately after multiplying two matrices:

    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)
        }
    }