Chapter 50 Unity Input Manager Input System (Part 1)

Unity's input system supports a variety of input devices, such as keyboards and mice, gamepads, touch screens, VR and AR controllers, and more. Unity provides input support through two separate systems: First, the Input Manager (Input Manager) is part of the Unity core platform, available by default, and belongs to the old unity input system. Second, the input system (Input System) is a package that must be installed through the Package Manager before it can be used. It belongs to the new unity input system. Of course, our course still starts from the old input system Input Manager.

Since the input is basically processed in the script, the code logic related to input processing is implemented in the Update method. Here we need to introduce the Input class provided by Unity, which provides many static variables and static methods for obtaining input information. In fact, in our previous chapter cases, we have also used this class to obtain keyboard input, for example: Input.GetKey(KeyCode.A) is used to determine whether the user has pressed the letter A key, that is to say, the GetKey method is It is used to obtain keyboard input, and its parameter is the key value of the keyboard, and these key values ​​are also constant values ​​that Unity has provided. Next, let's take a look at the variables and methods that the Input class provides us with.

First, let's take a look at the static variables in it.

anyKey Whether any key or mouse button is currently pressed.

anyKeyDown returns true the first frame after the user presses any key or mouse button.

inputString returns the keyboard input entered for this frame.

location Property for accessing the location of the device (handhelds only).

mousePosition The current pixel coordinate position of the mouse.

We just briefly introduce a few, we focus on the static methods of the Input class

GetKey returns true when the user presses the key identified by name.

GetKeyDown returns true during the frame the user begins pressing the key identified by name.

GetKeyUp returns true during the frame that the user releases the key identified by name.

The above three methods are mainly used to obtain keyboard keys. Next, we will use code to demonstrate. We create a new "InputManagerDemo" project, and then create the "InputScript.cs" script file in the default scene, as follows

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputScript : MonoBehaviour
{
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            Debug.Log("键值A");
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("按下键值A");
        }
        if (Input.GetKeyUp(KeyCode.A))
        {
            Debug.Log("按上键值A");
        }
    }
}

Then we attach the script to the camera "Main Camera", then run the project and press the key value A to test.

In the console, we have enabled the folding function, which is to display the same log in one line, and the number behind it is the number of times the same log is repeatedly output. We can find that when we press the key value A once, GetKeyUp and GetKeyDown will only be triggered once, while the GetKey method will be triggered multiple times according to the length of time the user presses. Regarding key value constants, we can also briefly explain, after all, there are not many commonly used keys on a keyboard.

KeyCode.A – KeyCode.Z represent 26 letters, so I won’t introduce them in detail.

KeyCode.Alpha0 - KeyCode.Alpha9 represent the number keys on the main keyboard.

KeyCode.Keypad0 - KeyCode.Keypad9 represent the numeric keys on the keypad.

KeyCode.F1 - KeyCode.F12 represent the function keys of F1-F12.

Backspace = Backspace; Delete = Delete; Tab = Indent; Escape = Escape; Space = Space; Return = Enter; RightShift = Right Shift; LeftShift = Left Shift; RightControl = Right Ctrl ;LeftControl = Left Ctrl key; RightAlt = Right Alt key; LeftAlt = Left Alt key; UpArrow = Up Arrow key; DownArrow = Down Arrow key; RightArrow = Right Arrow key; LeftArrow = Left Arrow key.

Regarding these key values, we don't need to deliberately remember them. In daily development, we will naturally remember them after using them more.

GetMouseButton Returns whether the given mouse button is pressed.

GetMouseButtonDown returns true for the frame that the user presses the given mouse button.

GetMouseButtonUp returns true during the frame the user releases the given mouse button.

The above three methods are mainly used to obtain the mouse buttons, where the parameter value is 0 for the left button, 1 for the right button, and 2 for the middle button. As for the position information of the mouse, it is obtained through the static variable mousePosition. The static variable is a three-dimensional vector Vector3 type, which corresponds to the x, y, and z coordinate values ​​of the game window coordinate system. Please note that the origin of the game window coordinate system is the lower left corner , and the z value is always 0. Next, we also use scripts to illustrate the information acquisition of mouse buttons.

        if (Input.GetMouseButton(0))
        {
            Debug.Log("鼠标左键");
            Debug.Log("鼠标位置:" + Input.mousePosition);
        }
        if (Input.GetMouseButton(1))
        {
            Debug.Log("鼠标右键");
        }
        if (Input.GetMouseButton(2))
        {
            Debug.Log("鼠标中键");
        }
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("鼠标左键按下");
        }
        if (Input.GetMouseButtonUp(0))
        {
            Debug.Log("鼠标左键按上");
        }

Next, we re-run the entire project, then press the left mouse button, right button and middle button in sequence, and then check the console output, the screenshot is as follows

Similar to the method of obtaining keyboard keys, for a mouse click event, the GetMouseButton method will be called multiple times, while GetMouseButtonUp and GetMouseButtonDown will only be called once. Input.mousePosition outputs position coordinate information. Please pay attention to the number of method calls when using it.

GetAxis Returns the value of the virtual axis identified by axisName.

GetAxisRaw Returns the value of the virtual axis identified by axisName (no smooth filtering applied).

GetButton Returns true when the virtual button identified by buttonName is pressed.

GetButtonDown returns true during the frame that the user presses the virtual button identified by buttonName.

GetButtonUp returns true the first frame the user releases the virtual button identified by buttonName.

The above method is mainly used for "virtual axis" and "virtual button". There are two types of keys that need to be used in the game. One is the on/off key, which is a key that can only have two states (press and press). The keys on the keyboard belong to this category. The other is the linear key (that is, the "axis" key), whose key value is in a range (such as between -1 and 1), such as the joystick that controls the front, rear, left, and right in the gamepad. Regardless of the "virtual axis" and "virtual button", the "Axes" input axis is uniformly used in Unity to represent (when the axis key only has -1 and 1, it is the button key). Unity's input axes are device-independent, and can be used for mice, keyboards, gamepads, and other devices. The keys of each device have their own numbered names, and they can all be set as corresponding input axes in Unity. Unity's input axis has a custom name, and the parameters of the GetAxis method and GetButton are the names of the input axes, but the return values ​​of the two methods are different.

bool Input.GetButton("virtual button"): This method can read the virtual button, regardless of whether the real bound key comes from the mouse, or keyboard, or other control devices. It only judges whether a key is pressed or lifted, and cannot judge whether the direction is left or right. Therefore, the return value of this method is a Boolean type.

float Input.GetAxis("virtual axis"): It can judge whether a key is pressed or lifted, and can also judge the direction. The return value is a floating point number between -1 and 1. The value of 0 means that no key is pressed. press. [-1,0) indicates that a key is pressed and the direction is left, (0,1] indicates that a key is pressed and the direction is right.

It can be seen that Unity's input shaft is a unified solution designed to solve various input devices. We click on the menu bar "Edit" -> "Project Settings...", and find "Input Manager" on the left side of the pop-up window, as follows

The first is the Size value, which represents Unity setting 18 different input axes. Of course, we can also modify this value and add our custom input axis. Next, we briefly introduce several input axes predefined by Unity. The first is the "Horizontal" horizontal axis and the "Vertical" vertical axis. They are mainly used for directional information input of front, rear, left, and right. Among them, "Horizontal" is the information input in the left and right directions, and "Vertical" is the information input in the front and rear directions.

 

Note that the configuration parameters are the same for each type of input axis. Let's briefly introduce it.

Name: Enter the name of the axis, which can be used directly in the script. For example: Input. GetAxis ("Vertical");

Descriptive Name: The name displayed when the input value is positive. Default is blank.

Negative Descriptive Name: The name displayed when the input value is negative. Default is blank.

Nagative Button: Negative button name. That is, we specify which key of the device to use to get negative input values. For the horizontal and vertical axes, they correspond to the arrow keys "left" and "down" on the keyboard.

Positive Button: The name of the positive button. In the same way, specify the key type of the device to use to obtain positive input values. For the horizontal and vertical axes, they correspond to the arrow keys "right" and "up" on the keyboard.

Why is there a difference between positive and negative? In fact, for the "virtual button", it only has two status values, so the positive and negative numbers are of little significance. However, for the "virtual axis", its return value is between "-1" and "1". If a positive number represents one direction, then a negative number represents the other direction, and the size of the value can also indicate the degree of pressing the button. Therefore, it is more appropriate to use positive and negative numbers to represent the two directions above a dimension. Note that the two plus and minus keys set can be keys on a keyboard, or buttons on a joystick or mouse. We only need to fill in the name of the device button. The "left", "right", "up", and "down" here correspond to the arrow keys on the keyboard. You should use the keyboard arrow keys to control the front, back, left, and right information input in many games.

Alt Negative Button: Alternative negative button name. In other words, we can also use other keys on the device to get negative input values. For the horizontal and vertical axes, these correspond to the letter keys "A" and "S" on the keyboard.

Alt Positive Button: Alternative positive button name. In the same way, specify to use other keys on the device to obtain positive input values. For the horizontal and vertical axes, they correspond to the letter keys "D" and "W" on the keyboard.

Obviously, the alternative button here is set to the letter key setting of "WASD" on the keyboard. You should use the "WASD" key on the keyboard to control the front, rear, left, and right information input in many games.

Gravity: Gravity. If the player stops the input, this input shaft will revert to neutral or 0 speed, in units per second.

Dead: Dead zone. On an analog controller, any value in this range will map to neutral and provide no input.

Sensitivity: Sensitivity. Enter the speed at which the axis moves to the target value. The units are units per second.

The above three items are mainly optimized settings for the input shaft.

Snap: Capture. If enabled, the value of that input axis will be reset to 0 when the button in the opposite direction is pressed. Enabled by default.

Invert: Reverse. If enabled, swaps positive and negative control keys. Not enabled by default.

The above two items are mainly the settings used by the input shaft.

Type: type. Set the input device type. Can be Key or MouseButton , Mouse Movement , Joystick Axis . Default is Key or MouseButton keyboard or mouse. All button (including gamepad buttons) inputs should be set to Key or MouseButton type, for mouse movement (not mouse click) and scroll wheel should be set to Mouse Movement type, and for joystick should be set to Joystick Axis type. If it is set to the Joystick Axis type, after we connect the gamepad device, we can use the joystick to control the front, rear, left, and right information input.

Axis: axis. Sets the input axis of the input device. For the horizontal and vertical axes, the corresponding two default values ​​are "X axis" and "Y axis". Of course, we can also choose other input axes. Among them, the first three are X axis for the X axis, Y axis for the Y axis, 3rd axis for the roller, and the latter are the input axes of the joystick.

JoyNum: joystick number. Sets which joystick on the device to use. The default is to accept input from all joysticks.

Next, let's take a look at the input axis settings for "Fire1", "Fire2", "Fire3" and "Jump".

According to the settings of Positive Button and Alt Positive Button, the input axis named "Fire1" corresponds to the left Ctrl key on the keyboard and the left mouse button. Similarly, the "Fire2" input axis corresponds to the left Alt key on the keyboard and the right mouse button. Similarly, the "Fire3" input axis corresponds to the left Shift key on the keyboard and the middle mouse button. Finally, the "Jump" input axis corresponds only to the space bar on the keyboard (there is no alternate key press).

        float x = Input.GetAxis("Horizontal");
        if (x != 0)
        {
            Debug.Log("Horizontal X :" + x);
        }
        float y = Input.GetAxis("Vertical");
        if (y != 0)
        {
            Debug.Log("Vertical :" + y);
        }
        bool ctrl = Input.GetButtonUp("Fire1");
        if (ctrl)
        {
            Debug.Log("ctrl :" + ctrl);
        }

Next, we can run the project, and then press the keyboard arrow keys or WASD keys to test the horizontal and vertical directions. We can also press the left Ctrl key or left-click the mouse to test the input of "Fire1". Screenshot below

Next is the settings corresponding to the three input axes of the left mouse button "Mouse X", the right mouse button "Mouse Y", and the middle mouse button "Mouse ScrollWheel". Let's look at the screenshot first

For the input of mouse movement, we don't need to specify Button , but should specify Type as Mouse Movement type , and then the corresponding Axis are "X axis", "Y axis", and "3 rd axis (Joystick and Scrollwheel)". In this way, we can use "Mouse X", "Mouse Y" and "Mouse ScrollWheel" to get the input information of mouse movement. So what data do they return? For "Mouse X" and "Mouse Y", it represents the moving direction of the mouse. Negative values ​​represent movement in the lower left direction, positive values ​​represent movement in the upper right direction, and the size of the value can be understood as an offset (the value is between -1 and 1. , representing the difference in mouse position before and after). And "Mouse ScrollWheel" represents the forward and backward scrolling direction of the middle mouse button, negative values ​​represent backward scrolling, and positive values ​​represent forward scrolling. We can use the code to verify.

        float mx = Input.GetAxis("Mouse X");
        if (mx != 0)
        {
            Debug.Log("Mouse X :" + mx);
        }
        float my = Input.GetAxis("Mouse Y");
        if (my != 0)
        {
            Debug.Log("Mouse Y :" + my);
        }
        float mz = Input.GetAxis("Mouse ScrollWheel");
        if (mz != 0)
        {
            Debug.Log("Mouse ScrollWheel :" + mz);
        }

Please note that Input.GetAxis("Mouse X") returns the offset of the mouse movement, not the mouse click event, nor the coordinates of the mouse position on the screen. This offset can be used to indicate the forward and backward movement direction of the mouse, which can be converted into a vector and applied to the game character control. There are many different ways to control orientation in our scene. Keyboard operation is the easiest way to move the game character. You only need to refer to your own coordinate system to move forward, backward, left, and right. There are two ways to control the movement of game characters with the mouse, one is to control the movement of game characters by mouse movement; the other is to control the movement of game characters by clicking the mouse. However, the code control logic of both is the same. The implementation logic of both of them converts the 2D coordinate position of the mouse into the 3D coordinate position in the scene, and then calculates the three-dimensional vector (offset) according to the two coordinate positions before and after. This three-dimensional vector is the direction in which the game character moves. Of course, the specific operation should be to rotate the game character to the target direction (the game character looks at the target point), and then move forward according to its own coordinate system. Therefore, the most important thing here is this three-dimensional vector representing the direction. This can be achieved using vector subtraction. The conversion from the 2D coordinate position of the mouse to the 3D coordinate position in the scene is done by a transformation matrix or a ray.

Summary: For key input, we can use GetButton, GetButtonDown, GetButtonUp to get the state of the key. The buttons here can be keyboards, mouse buttons, gamepad buttons, or other device buttons. These three methods are sufficient for game interaction. As for the acquisition of mouse position information, in fact, we don't use a lot. For NGUI, the event attributes of UI elements can already help us handle most of the interaction logic.

Next we found that Unity repeated several input axes for us.

Among them, Horizontal, Vertical, Fire1, Fire2, Fire3, Jump are defined repeatedly. But they are targeting gamepads. Let's take Horizontal as an example to view

We did not set the corresponding Button name, but set Type to Joystick Axis is the joystick, and set Axis to X axis to use the default input axis of the gamepad (the default X axis of the joystick). Set it to any joystick input in Joy Num. This will set the gamepad's default primary stick to Unity's "Horizontal" input axis. Then, we can use Input.GetAxis("Horizontal "); to get the input of the horizontal X-axis of the default main joystick of the gamepad. Similarly, Input.GetAxis("Vertical "); can also be used to obtain the input of the vertical Y axis of the default main joystick of the gamepad. Next, we are looking at the settings of Fire1, Fire2, Fire3, and Jump, taking Fire1 as an example

In the "Positive Button" item, the button name of the gamepad we set is "Joystick Button 0", which corresponds to the "A" button on the gamepad. And the Type item is set to the key type again. As shown below:

The picture above is the gamepad we often use. He has two joysticks, a directional pad, four buttons (ABXY) buttons, and of course there are LB, RB buttons and two trigger buttons on both sides of the front side. Each of these keys has its own name.

A: Joystick Button 0

B: Joystick Button 1

X: Joystick Button 2

Y: Joystick Button 3

LB:Joystick Button 4

RB:Joystick Button 5

……

Here we understand why we set the name of "Positive Button" in Unity to "Joystick Button 0". Next, the remaining three input axes of Fire2, Fire3, and Jump in Unity correspond to Joystick Button 1, Joystick Button 2, and Joystick Button 3 of the gamepad, which are the three buttons B, X, and Y in the above picture. Next, let's use the code to test

        float jx = Input.GetAxis("Horizontal");
        if (jx != 0)
        {
            Debug.Log("Joystick X :" + jx);
        }
        float jy = Input.GetAxis("Vertical");
        if (jy != 0)
        {
            Debug.Log("Joystick Y :" + jy);
        }
        bool a = Input.GetButtonUp("Fire1");
        if (a)
        {
            Debug.Log("Joystick A :" + a);
        }

This time we will connect the gamepad to Unity, and then run the current project, do not use the mouse and keyboard, directly use the default main rocker that rotates the gamepad, and press the A button to test.

The content involved in this course has been shared to Baidu Netdisk: https://pan.baidu.com/s/1e1jClK3MnN66GlxBmqoJWA?pwd=b2id

Guess you like

Origin blog.csdn.net/konkon2012/article/details/130599525