Rigidbody : making Drag affect only horizontal speed?

Hi there,

I’m using AddForce to make my character move, and I wan’t it to slow down naturally when I release the move key. I found that temporarily increasing drag did the trick BUT it also slowed down the FALL and JUMP animation, which is an undesirable effect.

So, the question is: How do I use drag constrained horizontally (or if there is any other way to counter “AddForce” to slow down my character gradually, and horizontally only).

Rigidbody.drag can’t be constrained, but you can create your own “drag” function in FixedUpdate: multiply the x and z velocity components by a value slightly lower than 1 each FixedUpdate, what reproduces a natural energy loss - something like this:

  var drag: float = 0.01; // drag factor
  private var rb: Rigidbody;

  function Start(){
    rb = GetComponent.<Rigidbody>();
  }

  function FixedUpdate(){
    var vel = rigidbody.velocity;
    vel.x *= 1.0-drag; // reduce x component...
    vel.z *= 1.0-drag; // and z component each cycle
    rigidbody.velocity = vel;
  }

The drag factor can range from 0 (no drag) to 1 (stops immediately).

I’ve seen the solution to reduce the speed by a factor as the accepted answer in several posts but from my experience it’s a very unreliable solution.

The “correct” way to get different drag along different axes is to apply the drag as a force whose magnitude is proportional to the velocity. For example, the following code would add a linear drag of drag to the forward direction of a rigidbody and a linear drag of drag*sideDragFactor in the side-directions.

public float drag = 1f;
public float sideDragFactor = 0.1f;
public float acceleration = 10.0f;
private Rigidbody2D rb;

private void FixedUpdate() {
    velocity = transform.InverseTransformDirection(rb.velocity);
    Debug.Log("velocity: " + velocity);

    float force_x = -drag * velocity.x;
    float force_y = -drag / sideDragFactor * velocity.y;
    rb.AddRelativeForce(new Vector2(force_x, force_y));

    if (Input.GetButton("Fire1") {
        rb.AddRelativeForce(new Vector2(rb.mass * acceleration, rb.mass * acceleration));
    }
}

If everything is implemented correctly the object should reach a final velocity of acceleration / drag in the forward direction and acceleration * sideDragFactor / drag. in the side-direction when you hold down the fire button.