How to damp `linearDamping` in horizontal (x/z) axes only in RealityKit's physics

4 weeks ago 30
ARTICLE AD BOX

In RealityKit, there's a linearDamping that slows down physics velocity with a "drag" effect (or it feels like making the air "thicker").

For example:

var body = PhysicsBodyComponent( shapes: [shape], density: 1, material: .generate( friction: 0.8, restitution: 0.8), mode: mode) // here body.linearDamping = 2.0

This slows down movement in all 3 axes. However, I'd prefer not to apply damping to the y axis, since it makes things fall more slowly. I don't want to change the whole scene's gravity, since damping should only apply to only some, but not all, entities. Also even if I increate the gravity, it wouldn't perfectly cancel out the "drag" effect in y axis, because gravity is constant, and drag force is changing based on velocity.

I tried using PhysicsMotionComponent and manually adjust its linearVelocity in update calls:

struct RLPhysicsDampingSystem: System { func update(context: SceneUpdateContext) { // ... // This is always nil, despite entities are moving guard var motion = entity.getComponent(PhysicsMotionComponent.self), else { continue } var linVel = motion.linearVelocity // Damping formula: e^(-d * dt) let linDamping = exp(-damping.horizontalLinearDrag * Float(delta)) linVel.x *= linDamping linVel.z *= linDamping motion.linearVelocity = linVel entity.components.set(motion)

However, it didn't work because PhysicsMotionComponent is always nil (apparently physicsBody and gravity moves the entity without auto-generating a PhysicsMotionComponent)

Read Entire Article