RealityKit and physics

I'm trying to get physics working in RealityKit. In Reality Composer I've created 3 spheres sitting on a thin ground cube which is surrounded by four walls. The spheres have physics set to dynamic and the ground and walls have physics set to static.

If I set sphereEntity.physicsBody.mode to .kinematic and set sphereEntity.physicsMotion.linearVelocity I can get the spheres to move but they go through the walls. I tried setting sphereEntity.physicsBody.mode to .dynamic and running sphereEntity.addForce([0.1, 0, 0]) but they don't move. I want to set the spheres moving but also bounce off the walls.
Answered by MarkH_ in 650825022
The problem was that I was giving the spheres so little linear velocity that it looked like setting the mode to .dynamic was stopping them but it was just friction. The following seems to work:

Code Block
sphere.physicsBody?.mode = .kinematic
sphere.physicsMotion?.linearVelocity = [.random(in: -3...3), 0, .random(in: -3...3)]
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.milliseconds(1)) {
sphere.physicsBody?.mode = .dynamic
}


In dynamic mode applyLinearImpulse() seems to work but the entity needs to be active. I don't know a good way to detect when an entity becomes active apart from a delay after an anchor is added to the session.

Code Block
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(1)) {
sphere.applyLinearImpulse([.random(in: -3...3), 0, .random(in: -3...3)], relativeTo: nil)
}
}


Accepted Answer
The problem was that I was giving the spheres so little linear velocity that it looked like setting the mode to .dynamic was stopping them but it was just friction. The following seems to work:

Code Block
sphere.physicsBody?.mode = .kinematic
sphere.physicsMotion?.linearVelocity = [.random(in: -3...3), 0, .random(in: -3...3)]
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.milliseconds(1)) {
sphere.physicsBody?.mode = .dynamic
}


In dynamic mode applyLinearImpulse() seems to work but the entity needs to be active. I don't know a good way to detect when an entity becomes active apart from a delay after an anchor is added to the session.

Code Block
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(1)) {
sphere.applyLinearImpulse([.random(in: -3...3), 0, .random(in: -3...3)], relativeTo: nil)
}
}


RealityKit and physics
 
 
Q