使用 Unity 的新输入系统检测鼠标滚轮滚动输入

Red*_*edi 5 c# user-input input mousewheel unity-game-engine

我目前正在尝试检测我当前在 Unity 引擎中进行的 2D 游戏的鼠标滚轮滚动输入。

我正在使用新的输入系统,目前我仍坚持使用以下代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem.Controls;

public class ZoomController : MonoBehaviour
{

private PlayerControls playerControls;

private void Awake()
{
    playerControls = new PlayerControls();
}


private void OnEnable()
{
    playerControls.Enable();
}

private void OnDisable()
{
    playerControls.Disable();
}

void Start()
{
    
}

void Update()
{

    if (playerControls.Land.Zoom.ReadValue<Vector2>().y >= 1)
    {
        Debug.Log("Scroll 1");
    } else if (playerControls.Land.Zoom.ReadValue<Vector2>().y <= -1)
    {
        Debug.Log("Scroll 2");
    }
    
 }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果我运行代码,什么也不会发生,我也不知道为什么。

And*_*s B 11

如果您将滚轮视为“1D 轴”,您需要告诉 Unity 哪一侧(向上或向下)应该获胜。否则,您只会收到始终为 0 的平均值。

作为 1D 轴的动作 - 告诉 Unity 哪一方获胜

另一个更好的选择是让值通过并添加“绑定”。 在此输入图像描述

在此输入图像描述

请注意,大多数系统上的默认滚动值是 120,但在 Linux 上似乎是 1。因此,我建议只需检查该值是否大于或小于 0 来决定是向上还是向下滚动。

float z = zoom.ReadValue<float>();
if (z > 0)
    Debug.Log("Scroll UP");
else if (z < 0)
    Debug.Log("Scroll DOWN");
Run Code Online (Sandbox Code Playgroud)

  • 请注意,鼠标滚轮是 2D 矢量,但 y 方向和 x 方向都是浮点数。如果您想同时读取两个值(作为 Vector2),则必须将操作定义为“2D Vector”。 (3认同)