Found interesting 2D movement code

Hello guys, today, I experimented a little bit and found this 2d movement code interesting :slight_smile:

        int keyW = Input.GetKey (KeyCode.W) ? 1 : 0;
        int keyS = Input.GetKey (KeyCode.S) ? 1 : 0;
        int keyA = Input.GetKey (KeyCode.A) ? 1 : 0;
        int keyD = Input.GetKey (KeyCode.D) ? 1 : 0; 

        rb2d.velocity = new Vector2 ((keyD - keyA) * speed, (keyW - keyS) * speed);

Sure it works but it’s not as intuitive as it could be (although it could be worse). As always readable code is more important than trying to shorten it as much as possible.

I started learning today, and I used this thing in Game maker so I wanted to post it :smile: :3

Well, it seems pretty intuitive to me (if you replace “keyw” by “up”, “keys” by “down”, that kind of stuff.) It shows clearly there can be only two states and the values of it.

wouldn’t you get essentially the same result with this?

        float xaxis = Input.GetAxisRaw("Horizontal");
        float yaxis = Input.GetAxisRaw("Vertical");

        rb2d.velocity = new Vector2(xaxis * speed, yaxis * speed);
1 Like

tried for 2d game and it didn’t work

@oly7447 check out this tutorial on movement