i’m new to unity so i’m trying to create a simple first person movement for my maze game but i don’t know how to check if the W/A/S/D key was pressed and i also don’t know how to move the X and Y bcz i’m also new to C# so i don’t have any idea on how to this and there are no good tutorials for me pls help i’ll also be happy for help with camera movement
Hello @Realfalafel, here is the method that I was taught.
First of all, to check for input from the keyboard, instead of checking each key, you can check for input along an axis. What this means is when the W or Up
Arrow key is pressed, this will be input along the Vertical (up, down) Axis. Or when the D or Right Arrow key is pressed, you would get input along the Horizontal (left, right) Axis.
Lets implement this. Go to Void Update, and create a local variable.
Just in case you don’t know what a local variable is, it is the same as a normal variable, except it is only used in it’s local method, so this variable is only useable in Void Update, not in Void Start, because it is local to Void Update. Also you don’t need to put a “public” or “private”, because this variable is always “private” to it’s method.
Now create your variable like this:
float _VerticalInput = Input.GetAxis("Vertical");
“.Input” is the pathway to the Input Manager, which allows you to check for any kind of input. Then you specify what kind of input you want, in this case we want to check the axis’s. Then we specified what Axis we wanted, in this example, the Vertical Axis.
Do this with the Horizontal Axis as well, your code should look like this:
float _VerticalInput = Input.GetAxis("Vertical");
float _HorizontaInput = Input.GetAxis("Horizontal");
Now, when D key is pressed, _HorizontalInput = 1, When A key is pressed, _Horizontal input = -1.
Now lets get your player moving. The position and rotation and scale of an object is called the Transform. Type this code below your variables.
transform.Translate(Vector3.up * _VerticalInput * Time.deltaTime);
transform.Translate(Vector3.right _HorizontalInput * Time.deltaTime);
Translate allows us to change our transform, Vector3 is a way of moving in 3D space. There is math behind this code but I will tell you about that in another post because this one is getting long.
Now if your script is attached to the player you should be able to move your player around but it will be slow, but I will explain that along with the math in another post and tell you how to speed it up.
Ok, that was long, but I hope that it was helpful.
Let me know if you have any questions.