Home > OS >  How to simulate touch/click in Unity with script
How to simulate touch/click in Unity with script

Time:09-24

I'm trying to make cursor with Unity, which moves with keyboard input. It will move with WSAD keys, and send touch event with Q Key. So What I want to do is something like:

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

Detecting touch is pretty easy, but how do I make touch events artificially?

Copy-pasting my already existing input handler (Using raycast on touch position, for example) would be also a solution, but I think there would be clearer solutions.

CodePudding user response:

It is far from perfect, but here is a jumping-off point on what you can do with the old input system.

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);
        }
    }
}

Set the KeyCode values to whatever you prefer. In my example, I set a UI image to the cursor and set the canvas renderer to Overlay, so the coordinates were already in screen space. I replaced the InputModule on the scenes EventSystem with this script.

Here is a gif of the script:

Example

I am moving my fake cursor around the screen using wasd and when I hit space, it simulates a click event on the position of the fake cursor.

  • Related