首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用脚本模拟触摸/单击

如何用脚本模拟触摸/单击
EN

Stack Overflow用户
提问于 2021-09-23 05:09:12
回答 1查看 3.1K关注 0票数 1

我试着用Unity做光标,它用键盘输入移动。它将用WSAD键移动,用Q键发送触摸事件。所以我想做的是:

代码语言:javascript
复制
if (Input.GetKeyDown(KeyCode.Q)
{
    // Is identical to touch/click the given position of screen for this frame.
    SendTouchEvent(currentCursorPos);
}

检测触摸是非常容易的,但是我如何人为地让触摸事件发生呢?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-23 06:18:29

这远不是完美的,但这里是一个起点,你可以用旧的输入系统做什么。

代码语言:javascript
复制
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,因此坐标已经在屏幕空间中。我用这个脚本替换了场景中的InputModuleEventSystem

下面是脚本的一个gif:

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69294323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档