- Home /
How to stop applying force when button is not pressed anymore
I'm kinda new to Unity, and programming in general. Am trying to make object go in all directions, and it works. The problem is next: when button is not pressed anymore, object will still move in wanted direction, with same amount of force.
I tried using applyStopForce(); which caused error, tried setting velocity and/or force to 0 on GetKeyUp etc.
void FixedUpdate ()
{
if (Input.GetKey(KeyCode.W)) {
rigidbody2D.AddForce(Vector2.up * forceConstant);
} else if (Input.GetKey(KeyCode.S)) {
rigidbody2D.AddForce(Vector2.up * -forceConstant);
}
if(Input.GetKey(KeyCode.A)){
rigidbody2D.AddForce(Vector2.right * -forceConstant);
}else if(Input.GetKey(KeyCode.D)){
rigidbody2D.AddForce(Vector2.right * forceConstant);
}
}
In your title, what do you mean by 'stop applying force'? Do you mean that you want the GameObject to begin slowing down when all the movement keys are released, or do you mean you want the GameObject to stop entirely as soon as all the movement keys are released?
Answer by Wondermike_2000 · Apr 06, 2014 at 09:14 AM
Hallo,
I use: rigidbody.Sleep(); to set force to 0.
Wondermike
thanks, what would be the best place to call Sleep function?
Answer by Darwin Mecharov · Apr 06, 2014 at 10:07 AM
You could put the Sleep function when the input key is held up. Like this:
if(Input.GetKeyUp(KeyCode.W))
{
rigidbody.Sleep();
}