UnityVR--Plugin 1--New InputSystem

Table of contents

New version of InputSystem

Install a new version of the InputSystem plugin

Configure the new InputSystem

Configure the new version of the input method in the project to move and fire

Add and bind move events

Add and bind fire event

Summary (a few words)


New version of InputSystem

  In the original Unity system, there were only common input devices such as keyboards, mice, and joysticks. However, with the continuous upgrading of digital products, more and more input methods appear in the game, such as mobile phones, XBox, and switches. There are also VR, AR equipment, etc., so the old InputSystem is no longer convenient, and the new InputSystem came into being. Moreover, the new InputSystem is based on the event-centric design method, which separates the input device from the action logic, and processes the input information through configuration and mapping, which is more in line with our current project design concept.

Install a new version of the InputSystem plugin

  In the previous article, we have used Input.GetAxis("Mouse X") and other methods many times, which are all set in the Input Manager that comes with Unity (location: Edit->ProjectSettings->InputManager)

   The new version of InputSystem can be in Window->PackageManager, select UnityRegistry, find InputSystem in the list, click Install, and wait for the automatic installation progress:

   After the download is complete, Unity will automatically install and restart, and you can see InputSystem in the Packages folder:

  After the installation is complete, some components need to be reset when using them. For example, when using UI controls, the EventSystem of the UI will display a warning. Just click the button and agree to use the new version of InputSystem:

In PackageManager->InputSystem, there are many examples that can be downloaded for reference:

Configure the new InputSystem

  1. In the menu Edit->ProjectSettings, select Player->OtherSettings->Configuration->Active Input Handling*, you can choose to use the old version or the new version of InputSystem, if you need both, you can choose "Both"

   2. In the same panel, select "InputSystemPackage" and click the "Create settings asset" button, so that a new InputSystem.inputsettings configuration file will be created under the Assets folder, and the settings in the InputSystemPackage panel will be recorded in this file middle

   

Configure the new version of the input method in the project to move and fire

  1. "Player Input" component: Click the "Add Component" button on the empty node of the scene to mount the "Player Input" component. It is recommended to mount on SingleMono, which is the node that mounts all Mono singleton scripts. It will not be eliminated when the scene is switched. For details, see ( Single Case )

 2. Create a new configuration file: Right-click on the folder where the Input script is placed, "Create->Input Actions (bottom)", set a name for the newly created configuration file, here is called "Input Controls", and then click "Edit asset "configuration file. For detailed explanation of configuration parameters, see ( Unity's new input system Input System (1) )

 

   3. Configure the input for Player movement: Press the "+" sign on "ActionMap" in the pop-up panel to create a new input configuration group. You can modify the name as needed, here it is changed to "PlayerMap". In the "Action" column on the right is the configuration for managing various inputs such as movement, firing, and clicking. You can also modify the name of "New Action" as needed:

   4. Bind the input. Here we take the movement of the protagonist on the field as an example. Its movement is on the XZ plane. Therefore, a two-dimensional vector input must be added to obtain the input value. In the "Action Type" on the right, select the type as "Value", and the "Control Type" below is Vector2

 

  5. Click the "+" sign on the right side of "Action->Move", add and bind a listener "Add Positive\Negative Binding", and a "2DVector" item will be added:

  Bindings in the four directions of up, down, left, and right will automatically appear under the "2D Vector". In the Path drop-down menu on the right, you can see various input devices. Select the appropriate input according to your needs, including joystick, keyboard, mouse... Just enter the button in the search bar directly, and use the W button here:

 

   6. Set the fire in the same way. It only needs to press a button to fire, so "Action Type" can be selected as "Button". Here, the fire button is set to the Space button:

 7. After the settings are complete, save and exit. Set the "Action" of the "Player Input" component on the SingleMono node to the InputControls file configured above.

   In DefaultMap, you can see the PlayerMap configured above, which is now the default input item.

 Add and bind move events

   1. Register and send events in the script, taking the protagonist's movement as an example.

    See (Event Center, InputManager) for details on the concept of events and the establishment of event centers, so I won't repeat them here. Just record about the movement of the protagonist, how to send movement data and realize movement by listening to events.

  (1) Modify the previously written HeroMove.cs ( component 2--Rigidbody--move control ), which is a script that hangs on the protagonist to control the movement of the protagonist, registers a movement event in it, and sends data (two-dimensional movement position vector)

public class HeroMove : MonoBehaviour
{
    private Rigidbody rb;
    private Vector2 moveInput;
    private Vector3 movement;
    private Quaternion targetRotation;
    public float moveSpeed = 2;
    public float rotateSpeed = 2;
    GameObject Bullet;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        //增加
        EventManager.Instance.AddEvent(EventType.OnPlayerMove, this, data =>
        { //注册一个移动的事件,这个事件由InputManager中的OnMove发送给
          //场景中的PlayerInput绑定监听
            var eventData = data as EventDataPlayerMove;
            moveInput= eventData.position; //传递移动时的XZ方向的位置
        });
    }

    void FixedUpdate()
    {
        //删除:
        //moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); //坐标数据不再由Input.GetAxis获得
        //下面都一样
        movement.Set(moveInput.x, 0, moveInput.y);//坐标数据通过事件数据发送
        movement.Normalize();
        //检测是否有输入
        bool hInput = !Mathf.Approximately(moveInput.x, 0);
        bool vInput = !Mathf.Approximately(moveInput.y, 0);
        if (hInput || vInput)
        {
            movement = Quaternion.Euler(0, Camera.main.transform.eulerAngles.y, 0) * movement;
        }
        Vector3 lookForward = Vector3.RotateTowards(transform.forward, movement, rotateSpeed * Time.fixedDeltaTime, 360);
        targetRotation = Quaternion.LookRotation(lookForward);
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
        rb.MoveRotation(targetRotation);
    }
}

  (2) Create a new script (or write directly in InputManager.cs) to add the function of sending events. (For definitions of SendEvent, EventType, InputManager, etc., see ( EventManager--Event Center 2 , InputManager )

public class InputManager : SingleMono<InputManager>
{
    //定义移动和开火的事件
    public void OnMove(InputAction.CallbackContext context)
    {//绑定新版InputSystem中的PlayerMap-Move事件
        EventManager.Instance.SendEvent(EventType.OnPlayerMove, new EventDataPlayerMove()
        {
            position=context.ReadValue<Vector2>()
        });
    }
    public void OnFire(InputAction.CallbackContext context)
    {//绑定新版InputSystem中的PlayerMap-Fire事件
        EventManager.Instance.SendEvent(EventType.OnPlayerFire, null);
    }
}

  2. Mount the above InputManager.cs on the singleton node on the field (all scripts that inherit SingleMono are hung here, see Singleton for details )

    (The following settings are the same as the button listening events in the UI)

  3. Below the "PlayerInput" component, set the event "Event". Here you can see the two input response items "Move" and "Fire" set above. Click the + sign below the two items respectively, and then bind the corresponding events set in the script:

  4. Drag the node (SingleMono) with the script that sends the event (now InputManager.cs) to the Object column:

   And click the small triangle in the monitoring function column, select the script name, and you will see the two monitoring functions defined above, which control movement here, so select the "OnMove" function:

 

 Add and bind fire event

  1. Register a firing event: Create a new script, mount it on the protagonist (other GOs are also available), register an event in it, and set the callback callback

public class BulletFireEvent : MonoBehaviour
{
        public GameObject bullet;
        void Start()
        {
            EventManager.Instance.AddEvent(EventType.OnPlayerFire, this, callback =>
            {
                bullet = Resload.Instance.LoadPrefab("Bullet");//从资源库加载
                bullet.SetActive(true);
                //赋予子弹初始值和角度
                bullet.transform.position = transform.position;
                bullet.transform.rotation = transform.rotation;
                Destroy(bullet, 2);//2秒后销毁
            });
        }
    }

  2. Set the OnMove function in Event->PlayerMap->Fire as above:

Summary (a few words)

  1. According to the above settings, the running effect is the same as that without using the new version of InputSystem and Event Center, so the picture of the running result is not displayed;

  2. The above script uses a custom event center (EventManager), which is an important part of project design (see EventManager--Event Center for details), of course, you can also use the event management defined by Unity;

  3. The monitoring function setting in PlayerInput can also be done in the script, which is very similar to the button monitoring in the UI system;

  4. If you need other functions, you can download the sample from Windows->PackageManager->InputSystem, and refer to its setting method;

  5. Advantages of using InputSystem: When we made the first-person controller, we used a lot of if to get the input button (see the first-person controller for details ). If you need to use the keyboard to input multiple times in the project, it is possible It is necessary to modify multiple keyboard keys, but to use InputSystem, you only need to directly modify the definition of the input method in the panel, which is very convenient!

Guess you like

Origin blog.csdn.net/tangjieitc/article/details/130864434