如何用操纵杆移动鼠标光标?

How to move mouse cursor with joystick?

这个问题好像已经讨论过很多次了。但是我找不到适合我的案例的解决方案。所有的讨论都是关于根据鼠标移动或通过鼠标控制对象的相机旋转。但是我需要用操纵杆(或键盘)来控制鼠标指针。这看起来是一个非常简单的问题,但我很困惑。目前,我正在尝试隐藏硬件光标并重新创建我自己的光标,用 Input.GetAxis("Horizontal")Input.GetAxis("Mouse X") 控制它,但光标刚刚消失,事件系统报告没有移动。但是,如果我使用 Input.mousePosition.x,我的自定义光标会很好地创建并用鼠标控制。不幸的是,我只需要用操纵杆来控制它。此外,它不适用于项目设置>>输入(或者我可能在那里更改了一些错误)提前致谢。

public class cursor : MonoBehaviour
{
    public Texture2D cursorImage;

    private int cursorWidth = 32;
    private int cursorHeight = 32;
    public float horizontalSpeed = 2.0F;
    public float verticalSpeed = 2.0F;

    void Start()
    {
        Cursor.visible = false;
    }

    void OnGUI()
    {
        float h = horizontalSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
        float v = verticalSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
        GUI.DrawTexture(new Rect(h, Screen.height - v, cursorWidth, cursorHeight), cursorImage);
    }
}

您正在使用

float h = horizontalSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
float v = verticalSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
GUI.DrawTexture(new Rect(h, Screen.height - v, cursorWidth, cursorHeight), cursorImage);

hv 将始终具有非常小的值,因为乘以 Time.deltaTimeInput.GetAxis afaik returns 通常值在 0 之间和 1.

这些值并不表示实际的光标位置,而是相对于上一帧的位置变化。

您的光标将停留在 top-left 角落的某处。


相反,您应该存储当前位置并添加您的值作为对它的更改

private Vector2 cursorPosition;

private void Start()
{
    Cursor.visible = false;

    // optional place it in the center on start
    cursorPosition = new Vector2(Screen.width/2f, Screen.height/2f);
}

private void OnGUI()
{
    // these are not actual positions but the change between last frame and now
    float h = horizontalSpeed * Input.GetAxis("Horizontal") * Time.deltaTime;
    float v = verticalSpeed * Input.GetAxis("Vertical") * Time.deltaTime;

    // add the changes to the actual cursor position
    cursorPosition.x += h;
    cursorPosition.y += v;

    GUI.DrawTexture(new Rect(cursorPosition.x, Screen.height - cursorPosition.y, cursorWidth, cursorHeight), cursorImage);
}

还要注意 horizontalSpeedverticalSpeedPixels / Seconds 中,您可能想要一些比 2 更大的值; )

我用了200& 键。