How to avoid movement speed stacking when multiple keys are pressed?

Posted by eren_tetik on Game Development See other posts from Game Development or by eren_tetik
Published on 2014-08-21T11:10:37Z Indexed on 2014/08/21 22:28 UTC
Read the original article Hit count: 176

Filed under:
|
|

I've started a new game which requires no mouse, thus leaving the movement up to the keyboard. I have tried to incorporate 8 directions; up, left, right, up-right and so on. However when I press more than one arrow key, the movement speed stacks (http://gfycat.com/CircularBewitchedBarebirdbat). How could I counteract this?

Here is relevant part of my code:

var speed : int = 5;

function Update () {
if(Input.GetKey(KeyCode.UpArrow)){
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else
        if(Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.RightArrow)){
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
    } else
        if(Input.GetKey(KeyCode.UpArrow) && Input.GetKey(KeyCode.LeftArrow)){
            transform.rotation = Quaternion.AngleAxis(315, Vector3.up);
    }
    if(Input.GetKey(KeyCode.DownArrow)){
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
    }
}

© Game Development or respective owner

Related posts about unity

Related posts about JavaScript