- Home /
Rigidbody.AddForce 2d movement without acceleration
I finally have movement working well enough in a game using a Rigidbody and the AddForce function, but I need to have no acceleration or deceleration. Adjusting the drag to a really high number doesn't work because it stops movement all together, or if the character can move then there is still minor acceleration/deceleration. Are there any other Rigidbody functions I should look at for this kind of problem? Is there another way to utilize AddForce that doesn't have this problem? Note a character controller simply will not do, this 2d character just cannot be "encapsulated" for it.
rigidbody.velocity.x is not working, I get "cannot modify return value because it is not a variable". I also tried using velocity.set(#,#,#) and that isn't resulting in anything happening
Forgot that you couldn't directly set a single axis of rigidbody. Updated the code to reflect that.
i coulda sworn i tried it before, but i tried it again and it worked. thanks
Glad to hear! You should accept an answer on this question btw ;)
Answer by aldonaletto · Dec 24, 2013 at 02:45 AM
A possible solution is to directly set rigidbody2d.velocity. If you want to move it horizontally and still keep the gravity effect, for instance, modify only the X component:
var curVel: Vector2 = rigidbody2d.velocity;
curVel.x = Input.GetAxis("Horizontal") * 5.0; // max speed = 5
rigidbody2d.velocity = curVel;
NOTE: You still may experience some acceleration/deceleration due to the internal filtering of GetAxis; if this is undesired, use Input.GetAxisRaw() instead.
Answer by Invertex · Dec 24, 2013 at 02:48 AM
One way would be to simply:
if ((Input.GetKeyUp("left")) || (Input.GetKeyUp("right")))
{
rigidbody.velocity = new Vector3(0,rigidbody.velocity.y,rigidbody.velocity.z);
}
That way whenever the player stops pressing a movement key, their X axis velocity will come to a stop. (you can add an if grounded statement in there too if you only want that happening on the ground)