Unity simple operation: InputSystem obtains WASD keyboard input to move characters

 

Table of contents

Install InputSystem

 Use the script generated by InputSystem in the edited script


Unity version: 2019.2.3f1

Install InputSystem

Menu bar/Window/Package Manager/Input System

 Right click in the project panel --> Create Input Actions 

 Select New Controls and rename it to PlayerControls and then press Edit asset in the properties panel

 Added Action Maps: PlayerMovement

 

Added Actions: New action renamed to MovementAction 

Properties item Modify ActionType=Pass Through

                        Modify ControlType = Vector2

 Click the + sign in the MovementAction item and select Add 2D Vector Composite

 

 Generate WASD

 Bind Up, Down, Left, Right, and so on

 Go back to the PlayerControls property panel and check Generate C# Class[*]

The project panel generates a PlayerControls.cs script 

 Use the script generated by InputSystem in the edited script

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

public class PlayerLocomotion : MonoBehaviour
{

    PlayerControls inputActions;//声明 InputSystem的脚本对象
    public new Rigidbody rigidbody;
    Vector2 movementInput;//存储 WASD输入的值

    [Header("Stats")]
    [SerializeField]
    float movementSpeed = 5;


    // Start is called before the first frame update
    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 vector3 = new Vector3(movementInput.x * movementSpeed, 0, movementInput.y * movementSpeed);
        rigidbody.velocity = vector3;//给刚体 这个方向的速度
    }


    public void OnEnable()
    {
        //获取设备上的输入
        if (inputActions==null)
        {
            inputActions = new PlayerControls();
            //绑定输入的值
            inputActions.PlayerMovement.MovementAction.performed += outputActions => movementInput = outputActions.ReadValue<Vector2>();
        }

        inputActions.Enable();//启用
    }

    public void OnDisable()
    {
        inputActions.Disable();//禁用
    }
}

 \

Finish

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_39114763/article/details/131353471