swiftswiftuirealitykit

How to move a model and generate its collision shape at the same time?


I have ModelEntity in SwiftUI and it moves. But the problem is: when adding generateCollisionShape method, it doesn't move anymore.

I want a collision effect as well as moving entity how can I attain both?

modelEntityClone.generateCollisionShapes(recursive: true)

modelEntityClone.physicsBody = PhysicsBodyComponent(massProperties: .default, 
                                                          material: .default, 
                                                              mode: .dynamic)

Solution

  • Hope this trick definitely helps. This physics lasts forever. ))

    enter image description here

    struct ARViewContainer: UIViewRepresentable {
        
        let ball = ModelEntity(mesh: .generateSphere(radius: 0.5))
        let anchor = AnchorEntity()
        
        func makeUIView(context: Context) -> ARView {
    
            let arView = ARView(frame: .zero)
    
            ball.physicsBody = .init()
            ball.physicsBody?.massProperties.mass = 0
    
            ball.physicsMotion = .init()
            ball.physicsMotion?.linearVelocity.x = 5.0
            ball.physicsMotion?.angularVelocity.z = -.pi
    
            ball.position.x = -4.0
            ball.generateCollisionShapes(recursive: true)
            anchor.addChild(ball)
    
            anchor.position.z = -3.0
            arView.scene.addAnchor(anchor)
            return arView
        }
    
        func updateUIView(_ uiView: ARView, context: Context) { }
    }