- Home /
Rigidbody2D and ForceMode.AddVelocity?
The new 2D update (Unity v4.3, released 2013-11-12) have come with the new Rigidbody2D component.
My previous code uses the 3D-based rigidbody, moving it using Rigidbody.AddForce(). I specified that the AddForce() uses ForceMode.VelocityChange, which conveniently ignores mass and just makes it better for a playable character.
Rigidbody2D.AddForce() on the other hand does not support ForceMode at all, it has only one way of dealing with velocity and that is 'force = mass * acceleration'.
Here's the part of my code that applies the target velocity to the rigidbody:
/* Apply motion */
Vector3 _velocity = myRigidbody.velocity;
Vector3 _velocityChange = (TargetVelocity - _velocity);
/* Move rigidbody */
myRigidbody.AddForce(_velocityChange,ForceMode.VelocityChange);
How to convert this movement to the Rigidbody2D? Preferably I am looking for an identical conversion, as I am quite keen on how the character feels right now when moving.
Answer by s_guy · Nov 14, 2013 at 02:10 AM
Yeah, no forcemodes (yet?) on Rigidbody2D. However, you should be able to the same result as ForceMode.VelocityChange by just adding your new velocity to the rigidbody2D.velocity.
Answer by Kencho · Dec 05, 2013 at 01:54 AM
Here are some extension methods for Physics2D to add this missing functionality to AddForce, strongly based on the solution by gfoot at this thread.
public static class Physics2DExtensions {
public static void AddForce (this Rigidbody2D rigidbody2D, Vector2 force, ForceMode mode = ForceMode.Force) {
switch (mode) {
case ForceMode.Force:
rigidbody2D.AddForce (force);
break;
case ForceMode.Impulse:
rigidbody2D.AddForce (force / Time.fixedDeltaTime);
break;
case ForceMode.Acceleration:
rigidbody2D.AddForce (force * rigidbody2D.mass);
break;
case ForceMode.VelocityChange:
rigidbody2D.AddForce (force * rigidbody2D.mass / Time.fixedDeltaTime);
break;
}
}
public static void AddForce (this Rigidbody2D rigidbody2D, float x, float y, ForceMode mode = ForceMode.Force) {
rigidbody2D.AddForce (new Vector2 (x, y), mode);
}
}
Answer by slake_it · Mar 02, 2016 at 10:00 AM
Force mode has been added 2d rigidbodies
As of version 5.61f1, still only half-implemented, and missing the mass-ignoring modes (Acceleration and VelocityChange)... Sincerely, can't see why unity doesn't use the good old Force$$anonymous$$ode type for both 3D and 2D.