找回密码
 立即注册
查看: 515|回复: 0

Unity NewInputSystem 实现鼠标移动监听及键盘

[复制链接]
发表于 2022-2-16 19:17 | 显示全部楼层 |阅读模式

  • 首先Window->Package Manager,搜索Input System安装。


2. Edit->Project Settings->Player->Other Settings->Active Input Handling,改成new或者both。
3. Unity的Project中右键->Create->Input Actions。
4. Action Maps取名,如Player。Actions右边小“+”添加New action,取名如:Action_Move,表示鼠标移动。此时对应Properties->Action->Action Type: Pass Through; Control Type: Vector 2. 继续添加Binding:Mouse->Positions.


5. 设置鼠标触发事件。New action:Action_Down,表示鼠标按键按下触发。此时对应Properties->Action->Action Type: Button. 继续添加Binding:Mouse->Left Button.


6. 同理设置鼠标抬起触发以及长按触发。其中Longpress需要考虑到Binding->Trigger Behavior: Press and Release, 表示按键按下直到松开都执行操作。


7. 尝试键盘控制。New action:kbd_Move,此处点击"+"选择Add 2D Vector Composite。此时对应Properties->Action->Action Type: Button. 继续添加Binding:Mouse->Left Button. 此时对应默认的Properties->Composite->Composite Type: 2D Vector; Mode: Digital Normalized.


继续修改Binding->Path, 可以设置为WSAD控制。
8. Save Asset,当在Project中再次点击此Actions时可以在Inspector中选择Generate C# Code。
9. unity中新建任意object,套上代码,即可运行,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyInputSmallTest : MonoBehaviour
{
    // MyInputActions为自己的Action名字
    public MyInputActions inputActions;
    private void Awake()
    {
        inputActions = new MyInputActions();
        inputActions.Enable();
        // 键盘控制移动,且inputActions必须配合+=,-=使用
        inputActions.Player.KBD_MOVE.performed += ctx =>
        {
            transform.Translate(ctx.ReadValue<Vector2>());
        };
        inputActions.Player.ACTION_DOWN.performed += ctx =>
        {
            Debug.Log("Action_Down" + UnityEngine.InputSystem.Mouse.current.position.ReadValue());
        };
        // 鼠标移动时即时反馈坐标
        inputActions.Player.ACTION_MOVE.performed += ctx =>
        {
            Debug.Log("Action_Move" + ctx.ReadValue<Vector2>());
        };
        inputActions.Player.ACTION_UP.performed += ctx =>
        {
            Debug.Log("Action_Up" + UnityEngine.InputSystem.Mouse.current.position.ReadValue());
        };
    }

    void Start(){}
    void Update(){}

    private void OnDestroy()
    {
        inputActions.Disable();
    }
}
// 源自某一篇博客,仅给自己做笔记10. 官方文档:https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Installation.html
超详细讲解:https://gamedevbeginner.com/input-in-unity-made-easy-complete-guide-to-the-new-system/#input_system_get_mouse_position
详细讲解各个Binding等,随时查阅。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 19:37 , Processed in 0.070547 second(s), 23 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表