问题描述
我目前正在尝试为我目前在 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");
}
}
}
如果我运行代码什么也没有发生,我不知道为什么。
解决方法
如果您将滚轮视为“一维轴”,您需要告诉 Unity 哪一侧(向上或向下)应该获胜。否则,您只会收到一个始终为 0 的平均值。
请注意,大多数系统上的默认滚动值是 120,但在 Linux 上它似乎是 1。因此,我建议简单地检查该值是否大于或小于 0,以确定它是向上还是向下滚动。
float z = zoom.ReadValue<float>();
if (z > 0)
Debug.Log("Scroll UP");
else if (z < 0)
Debug.Log("Scroll DOWN");
,
单独使用代码可以做到这一点:
Vector2 vec = Mouse.current.scroll.ReadValue();
scroll = vec.y