Making the HandleXXX() routines smaller

Hi,

as I didn’t like too many ‘if’ statements I changed the HandleMovement() and HandleRotation() methods to make them a little smaller:

    private void HandleMovement()
    {
        Vector3 inputMoveDir = new Vector3(0,0,0);

        inputMoveDir.z = System.Convert.ToSingle(Input.GetKey(KeyCode.W)) - System.Convert.ToSingle(Input.GetKey(KeyCode.S));
        inputMoveDir.x = System.Convert.ToSingle(Input.GetKey(KeyCode.D)) - System.Convert.ToSingle(Input.GetKey(KeyCode.A));

        float moveSpeed = 10f;
        Vector3 moveVector = transform.forward * inputMoveDir.z + transform.right * inputMoveDir.x;
        transform.position += moveVector * moveSpeed * Time.deltaTime;        
    }

To explain: As Input.GetKey() already returns 1 if pressed (because true == 1) I convert it to a Single (you can’t substract a bool from a bool and have to convert it to a float) and calculate vector.y through that: e.g.:

if nothing is pressed inputMoveDir.z is 0f - 0f = 0f, so nothing moves.
if “W” is pressed inputMoveDir.z is 1f (1f - 0f)
if “Q” is pressed inputMoveDir.z is -1f (0f - 1f)

So you skip 4 if statements, if you add the code for A and D.

HandleRotation() works the same way. I still have to figure out how to do this with HandleZoom(), but it should be doable also.

2 Likes

That is certainly one way of doing it.

You have to consider if it is quicker to check whether or not a key is pressed vs. checking whether or not it’s pressed, converting it to a single and then subtracting it from another value. While this is currently trivial, it is something that affects performance.

Unity provides Input.GetAxis("Horizontal") and Input.GetAxis("Vertical") which does pretty much the same thing: It gives you a value between -1 and 1 for the axis.

Later we’ll be implementing the new input system, too, so this may change again

1 Like

Privacy & Terms