How to apply quadratic drag force to a body in cannon.js?

811 Views Asked by At

I want to apply a drag force to a cannon.js' body, I've tried in a way but it's breaking the physics, wanted to know if there is a more correct way or if someone has already done something similar.

There is a property of the body called linearDamping, it's a drag force linearly proportional to the velocity, however I am trying to implement the fluid drag force formula, to achieve more realism.

The simplified formula is this one, as you can see it's quadratically proportional to the velocity:

Fd = - Constant * getMagnitude(velocity)**2 * normalize(velocity)

I have implemented in the cannon.js this way, using the Vec3 methods. Note that I call applyDrag every update:

applyDrag(coefficient) {
  const speed = body.velocity.length()

  const dragMagnitude = coefficient * Math.pow(speed, 2)

  const drag = body.velocity.clone()
  drag.scale(-1, drag)

  drag.normalize()

  drag.scale(dragMagnitude, drag)

  body.applyLocalForce(drag, new CANNON.Vec3())
}

However this sorta breaks, and the objects go crazy. Is there a better way to apply some sort of quadraticDamping?

This is the part where linearDamping is applied, I am having difficulties understanding fully that code and trying to implement a quadratic damping the right way.

1

There are 1 best solutions below

0
On

Solved! I didn't get that also the direction of the force vector is local, here is the solution:

applyDrag(coefficient) {
  const speed = body.velocity.length()

  const dragMagnitude = coefficient * Math.pow(speed, 2)

  const drag = body.velocity.clone()
  drag.scale(-1, drag)

  drag.normalize()

  drag.scale(dragMagnitude, drag)

  const centerInWorldCoords = body.pointToWorldFrame(new CANNON.Vec3())
  body.applyForce(force, centerInWorldCoords)
}