# When two movement buttons are held, the movement stops?

I am making a 2D game, and when I held the key “w”, the player goes forward, but when I hold both “w” and “a”, the movement stops completely.

Here is my script:

``````var speed = 4;
function Update() {
// Make the character walk forward if "w" is being held
if(Input.GetKey("w")) {
rigidbody.velocity = transform.forward * speed;
}
//  Stop the movement if "w" is not being held
if(Input.GetKeyUp("w")) {
rigidbody.velocity = transform.forward * 0;
}

// Make the character walk forward if "s" is being held
if(Input.GetKey("s")) {
rigidbody.velocity = transform.forward * -speed;
}
//  Stop the movement if "s" is not being held
if(Input.GetKeyUp("s")) {
rigidbody.velocity = transform.forward * 0;
}

// Make the character walk left if "a" is being held
if(Input.GetKey("a")) {
rigidbody.velocity = transform.right * -speed;
}
//  Stop the movement if "a" is not being held
if(Input.GetKeyUp("a")) {
rigidbody.velocity = transform.right * 0;
}

//Make the character walk right if "d" is being held
if(Input.GetKey("d")) {
rigidbody.velocity = transform.right * speed;
}
//  Stop the movement if "d" is not being held
if(Input.GetKeyUp("d")) {
rigidbody.velocity = transform.right * 0;
}
}
``````

PLEASE MAKE THE CODE BETTER! I AM NEW!

The way your code is structured, the last key detected wins, and you process them in WSAD order. Instead of assigning a vector to velocity, a vector can be built by adding together the vectors for any keys pressed:

``````#pragma strict

var speed = 4;
function Update() {
var v3Move = Vector3.zero;
// Make the character walk forward if "w" is being held
if(Input.GetKey(KeyCode.W)) {
v3Move += transform.forward;
}

// Make the character walk forward if "s" is being held
if(Input.GetKey(KeyCode.S)) {
v3Move -= transform.forward;
}

// Make the character walk left if "a" is being held
if(Input.GetKey(KeyCode.A)) {
v3Move -= transform.right;
}

//Make the character walk right if "d" is being held
if(Input.GetKey(KeyCode.D)) {
v3Move += transform.right;
}
rigidbody.velocity = v3Move * speed;
}
``````

Pressing both A & D keys will assign both the left and right vectors cancelling sideways movement. Same with the W and S keys for forward and back. But angle movement will now work.

Well I got a less complicated answer than the other answer, I was able to work this out:

``````var speed = 4f;
function Update()
{
rigidbody.velocity = Vector3.zero; //Clear movement from previous frames. May not be correct, but whatever makes a blank vector.
if(Input.GetKey("w"))
{
rigidbody.velocity += transform.forward * speed;
}
if(Input.GetKey("s"))
{
rigidbody.velocity += transform.forward * -speed;
}

if(Input.GetKey("d"))
{
rigidbody.velocity += transform.right * speed;
}
if(Input.GetKey("a"))
{
rigidbody.velocity += transform.right * -speed;
}
}
``````