When "W" is held, the character moves forward, but when "W" and "A" is held, movement completely stops

Posted by Vlad1k on Game Development See other posts from Game Development or by Vlad1k
Published on 2013-07-03T06:46:35Z Indexed on 2013/07/03 11:19 UTC
Read the original article Hit count: 409

Filed under:
|
|

I am making a 2D game, and when I hold the key "w", the player goes forward, but when I hold both "w" and "a", the movement stops completely, when I want it to go forward, while shifting to the left.

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!

EDIT: Here is a video to show my problem. http://www.screenr.com/3oxH

Here is the newest code:

var speed = 4f;
function Update() {
    if(Input.GetKey("w")) {
        rigidbody.velocity = transform.forward * speed;
    } else if(Input.GetKey("s")) {
        rigidbody.velocity = transform.forward * -speed;
    } else if(Input.GetKey("a")) {
        rigidbody.velocity = transform.right * -speed;
    } else if(Input.GetKey("d")) {
        rigidbody.velocity = transform.right * speed;
    }
    if(Input.GetKeyUp("w")) {
        rigidbody.velocity = transform.forward * 0;
    }
    if(Input.GetKeyUp("s")) {
        rigidbody.velocity = transform.forward * 0;
    }
    if(Input.GetKeyUp("a")) {
        rigidbody.velocity = transform.right * 0;
    }
    if(Input.GetKey("d")) {
        rigidbody.velocity = transform.right * speed;
    }
    if(Input.GetKeyUp("d")) {
        rigidbody.velocity = transform.right * 0;
    }
}

© Game Development or respective owner

Related posts about unity

Related posts about JavaScript