Touch screen programming

Hello there, I recently passed my Computer Games Development degree at University and I’m looking to expand upon what I learned during the course. During the course I used Unreal Engine, so I am new to Unity. I would like to know how to set up touch screen buttons that react in the same way as keyboard keys do, such that instead of pressing the Up Arrow on the keyboard, I can click on an up button displayed on the screen. I’ve looked at Unity’s tutorials and cannot find any on this topic. Thanks in advance.

Alex

I think that Unity’s standard assets (precisely CrossPlatformInput) is a great place to start.

You could achieve this by attaching a script to each virtual keyboard key that implements interfaces IPointerDownHandler and IPointerUpHandler from UnityEngine.EventSystems namespace. They could notify parent script through events or simple method calls that they’re being pressed.

For directional movement it’s better to just create a invisible virtual analog stick to where user presses and comparing the position delta to the starting point of the press for the duration of the press.

These answers are answering what he actually asked in a literal way, but probably not what he actually needs.

I think the real question is simply, how to react to touches of on-screen buttons? And that is very easy to do, and very well covered by the UI tutorials.

A slightly more interesting question is: how to react to keyboard events in the same way you react to UI events? For that, I use the following little script, attached to any object in the scene.

using UnityEngine;
using UnityEngine.Events;
using System.Collections.Generic;

public class KeyTrigger : MonoBehaviour {
    [System.Serializable]
    public class Element {
        [Tooltip("Key this event is triggered by.")]
        public KeyCode keyCode;
        [Tooltip("Event to fire when the key is pressed.")]
        public UnityEvent keyDownEvent;
        [Tooltip("Event to fire when the key is released.")]
        public UnityEvent keyUpEvent;
    };

    [Tooltip("List of key/event combinations.")]
    public List<Element> elements = new List<Element>(1);

    void Update() {
        foreach (var elem in elements) {
            if (Input.GetKeyDown(elem.keyCode)) elem.keyDownEvent.Invoke();
            if (Input.GetKeyUp(elem.keyCode)) elem.keyUpEvent.Invoke();
        }
    }
}