Optimizing Input Code
While it may not be necessary or vital for this specific case, learning to and practicing code optimization is a great thing to do.
Simplifying code reduces the number of moving parts during a game, and the fewer moving parts there are, the fewer possibilities of there being bugs.
So here’s the old code commented out with the new code directly below:
Now we’re making a new Vector3 and in place of the x and y coordinates putting the respective variables for horizontal and vertical inputs
One new Vector3 instead of two Vector3s.
And then building off of that, declare a local Vector3 as
new Vector3(horizontalInput, verticalInput, 0);
Think about it — what does the new Vector3 do, anyway?
Determines the direction the Player object goes!
In 2D space, exclusively along the (x, y) axis, there are only four main directions you can go along the 2 axes:
- left (-)
- right (+)
- up (+)
- down (-)
And of course, diagonally is possible when pushing up/right, down/right, down/left, up/left.
So by declaring a variable called direction and assigning it the value of the new Vector 3, you clean up the code in a bit.
In this particular case it’s more about aesthetics and keeping clean code (which we’ll get more into later), but I wanted to share this nifty hint with you.
It’s all about logic and what makes sense. Coming into it new, it can take some time to grasp and understand it, but if you keep at it, it will come and you’ll have many “ah-ha!!” moments.