Rotating a RealityKit Object around an arbitrary point rather its center point?

189 Views Asked by At

I am working on VisionOS app and I have a RealityView that calls a scene created in RealityComposer Pro. I have added drag and rotate gestures to my object. The gestures work fine but I want to be able to rotate from a selected point on the object rather than the default center point.

An example would be if I had cube I and I select the corner the rotation would happen around the corner point instead of the center point

1

There are 1 best solutions below

1
Andy Jazz On

Use rotation3DEffect(..) instance method that allows you to rotate the whole view containing a model in three dimensions around the specified axis (with specified pivot point called anchor).

enter image description here

For anchor parameter, you can use UnitPoint3D(x:y:z:) initializer:

import SwiftUI
import RealityKit

struct ContentView: View {
    @State var rotate: Angle = .zero
    
    var body: some View {
        VStack {
            RealityView { content in
                let box = ModelEntity(mesh: .generateBox(size: 0.15))
                box.generateCollisionShapes(recursive: true)
                box.components[InputTargetComponent.self] = .init()
                content.add(box)
            }
            .onTapGesture {
                withAnimation(.smooth(duration: 1.5)) {
                    if rotate.degrees == 0 {
                        rotate.degrees += 360
                    } else {
                        rotate.degrees -= 360
                    }
                }
            }
            .rotation3DEffect(rotate, axis: .y, anchor: .bottomBack)
        }
    }
}