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);
		}


	}

Hallo,

I use:
rigidbody.Sleep();
to set force to 0.

Wondermike

You could put the Sleep function when the input key is held up. Like this:

if(Input.GetKeyUp(KeyCode.W))
{
    rigidbody.Sleep();
}