Make 2D movement more precise and less based off of forces and physics

Alright, so I’ve been looking through all of the things Unity has on movement and 2D movement. I’ve looked at other people’s examples, and I’ve looked through countless code snippets, but I cannot for the life of me find a way to make my character’s movement precise.

By precise, I mean, have it stop the second you let go of a key, and begin the second you push down on a key. I don’t want it to accelerate or decelerate. I want it to move at a set value constantly.

Right now, I’ve got it setup this way:

	void Update () 
	{
		//cache vertical input
		float vertical = Input.GetAxis("Vertical");

		//assign vertical input as a vector 2 value
		Vector2 movement = new Vector2 (0.0f, vertical);

		//use vector 2 value to add force
		rigidbody2D.AddForce (movement);
	
	}

Using this, I get movement, but it is weighty and the character does not stop moving after input is pressed because a force is still acting on the player character.

I have tried alleviating this in a number of ways.

One of these was to set up a simple set of if/else statements in order to find input, and then to assign a rigidbody2D.velocity.y directly, like below:

	float speed = 10;
	

	// Update is called once per frame
	void Update () 
	{

		if (Input.GetKey("w"))
	    {
			rigidbody2D.velocity.y = speed;
		}
		else if (Input.GetKey("s"))
		{
			rigidbody2D.velocity.y = speed * -1;
		}
		else
		{
			rigidbody2D.velocity.y = 0;
		}
	
	}

This however pops up with an error in Unity asking me to store the variable in a temporary variable. And so, I have tried to do this by writing it this way:

	float speed = 10;
	

	// Update is called once per frame
	void Update () 
	{
		Vector2 velocity = rigidbody2D.velocity;
		rigidbody2D.velocity = velocity;

		if (Input.GetKey("w"))
	    {
			velocity.y = speed;
		}
		else if (Input.GetKey("s"))
		{
			velocity.y = speed * -1;
		}
		else
		{
			velocity.y = 0;
		}
	
	}

However, when I do this, I try to move the character with “w” or “s” and nothing happens, it is stationary. Any help you guys could give me would be greatly appreciated!

Input.GetAxis(“Vertical”) is smoothed. You can either go to the Input Manager and remove that smoothing or use Input.GetAxisRaw(“Vertical”).

And… you need to move this line:

rigidbody2D.velocity = velocity;

down to after you modified velocity, so you actually change it on the rigidbody.

The physics and collision processes run in sync with FixedUpdate.

http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.FixedUpdate.html

I was having issues with this until I changed all my Updates to FixedUpdates, and that fixed a lot of it. Also, what HappyMoo said. Move this:

rigidbody2D.velocity = velocity;

To after the code that directly changes velocity. The way you have it now will just change rigidbody2D.velocity back to itself, which obviously wouldn’t do anything.