Rigidbody.velocity and controls

Hello. I am having a problem controlling my 2d top-down character. I wanted to avoid transform.* in order to optimize collisions. However, with Rigidbody.velocity I seem to have a slightly different behaviour from unity. Please don’t consider the fact that if you release the key the character will still move, I’m aware of that. The strange thing is that if I press, say, W, and then at the same time I press S, the character will move down, and if I release S, and W is still being pressed, the character reverts to its upward movement (as expected). But it doesn’t work the other way around. If I press S, and move down, and then press W at the same time, it won’t move up. I gather it must have to do with the if statement execution order, as if I swap them it works exactly the opposite way. I am missing something obvious, am I not?

Thank you for your help!

#pragma strict

var speed : float;
var r : Rigidbody;

function Update()
{
    if (Input.GetKey("w"))
    {
        r.velocity.y = speed;
    }
    if (Input.GetKey("s"))
    {
        r.velocity.y = -speed;
    }
}

You should use Unity - Scripting API: Rigidbody2D.AddForce instead of directly modifying the velocity property.

The difference is
velocity = … just sets the velocity of the object to a new fixed value.
AddForce applies (add or subtract or whatever the force is about) a value to the current velocity of the object - instead of replacing the current value.

Thank you.
Unfortunately by doing so I run into different issues, such as parabolic movements due to momentum and inertia. I will try something though.

If you really would like to use velocity you would have to rethink you key validation logic.
It doesn’t make much sense to validate the keys for up and down. Use

else if (Input.GetKey("s"))

If both keys are pressed obv. one of them has to take precedence.

[e]
Or calculate a resulting value from both keys.

Like

float vertMove

if w then
vertMove++

if w then
vertMove--

velocity.y = vertMove

Just tried that, with some customization, and it works okay, thank you! Didn’t think about that. However, this adds velocity every frame, and it’s exactly what makes my rigidbodies vibrate on collision. Which is the main problem. I would rather not script a collision-proximity detection, so I was trying to find a solution that adds velocity ONCE and in some way detects key release to invert or zero out velocity.