【问题标题】:How to simulate touch/click in Unity with script如何使用脚本在 Unity 中模拟触摸/单击
【发布时间】:2021-09-23 14:18:29
【问题描述】:

我正在尝试使用 Unity 制作光标,它会随着键盘输入移动。 它会用 WSAD 键移动,并用 Q 键发送触摸事件。所以我想做的是:

if (Input.GetKeyDown(KeyCode.Q)
{
    // Is identical to touch/click the given position of screen for this frame.
    SendTouchEvent(currentCursorPos);
}

检测触摸很容易,但我如何制作人为的触摸事件?

复制粘贴我已经存在的输入处理程序(例如,在触摸位置使用光线投射)也是一种解决方案,但我认为会有更清晰的解决方案。

【问题讨论】:

  • 或者你可以使用new Unity input system 来创建事件处理代码,你可以直接从你的代码中触发这些事件。

标签: c# unity3d


【解决方案1】:

它远非完美,但这里是您可以使用旧输入系统做什么的起点。

using UnityEngine;
using UnityEngine.EventSystems;

public class TestScript : StandaloneInputModule
{
    [SerializeField] private KeyCode left, right, up, down, click;
    [SerializeField] private RectTransform fakeCursor = null;

    private float moveSpeed = 5f;

    public void ClickAt(Vector2 pos, bool pressed)
    {
        Input.simulateMouseWithTouches = true;
        var pointerData = GetTouchPointerEventData(new Touch()
        {
            position = pos,
        }, out bool b, out bool bb);

        ProcessTouchPress(pointerData, pressed, !pressed);
    }

    void Update()
    {
        // instead of the specific input checks, you can use Input.GetAxis("Horizontal") and Input.GetAxis("Vertical")
        if (Input.GetKey(left))
        {
            fakeCursor.anchoredPosition += new Vector2(-1 * moveSpeed, 0f);
        }

        if (Input.GetKey(right))
        {
            fakeCursor.anchoredPosition += new Vector2(moveSpeed, 0f);
        }

        if (Input.GetKey(down))
        {
            fakeCursor.anchoredPosition += new Vector2(0f, -1 * moveSpeed);
        }

        if (Input.GetKey(up))
        {
            fakeCursor.anchoredPosition += new Vector2(0f, moveSpeed);
        }

        if (Input.GetKeyDown(click))
        {
            ClickAt(fakeCursor.position, true);
        }

        if (Input.GetKeyUp(click))
        {
            ClickAt(fakeCursor.position, false);
        }
    }
}

KeyCode 值设置为您喜欢的任何值。在我的示例中,我将 UI 图像设置为光标并将画布渲染器设置为 Overlay,因此坐标已经在屏幕空间中。我用这个脚本替换了场景中的InputModule EventSystem

这是脚本的 gif:

我正在使用wasd 在屏幕上移动我的假光标,当我点击space 时,它会模拟假光标位置上的点击事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多