I'm building a RealityKit application where I want to spawn a floating object into my scene, in dynamic mode, which is not affected by gravity. It needs to collide with other objects, have a mass of 1, and be affected by an impulse, which is why I've made it dynamic.
Currently the object spawns into the scene at the correct point, but immedately falls to the floor due to a gravitational force being applied. I've been stuck on this for a while now, and can't find anything on how to remove this gravitational force.
Here's how I'm creating and spawning the object;
// Create the object entity
let object = ModelEntity(mesh: MeshResource.generateBox(size: [0.07, 0.01, 0.14]), materials: [SimpleMaterial(color: .white, isMetallic: false)])
// Define object shape
let objectShape = [ShapeResource.generateBox(size: [0.07, 0.01, 0.14]]
// Create the object PhysicsBody
var objectPhysicsBody = PhysicsBodyComponent(shapes: objectShape, mass: 1, material: .default, mode: .dynamic)
// Create the object CollisionComponent
let objectCollision = CollisionComponent(shapes: objectShape)
// Set components to the object
object.components.set(objectPhysicsBody)
object.components.set(objectCollision)
// Attach the object to the anchor
anchor.addChild(object)
One thing I have tried is applying a constant negating force to the standard gravitational force, however this didn't work as intended. It does apply an opposite force, but it is increasing so gradually ends up sending the object flying upwards
This is what I tried;
var displayLink: CADisplayLink?
// Main view loaded function
override func viewDidLoad() {
super.viewDidLoad()
// Repeatedly call the update function
displayLink = CADisplayLink(target: self, selector: #selector(update))
displayLink?.add(to: .current, forMode: .common)
...
}
…
// Repeatedly call applyAntiGravity
@objc private func update() {
applyAntiGravityForce()
}
private func applyAntiGravityForce() {
guard let ballPhysicsBody = object.physicsBody else { return }
let gravity: SIMD3<Float> = [0, -9.8, 0]
let antiGravityForce = -gravity
ball.addForce(antiGravityForce, relativeTo: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
displayLink?.invalidate()
}