Character movement via on-screen touch controller input | Rigidbody | Unity Game Engine


TouchController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TouchController : MonoBehaviour
{
    public static float Horizontal = 0, Vertical = 0;

    void Awake()
    {
        SetupButton(transform.Find("up").gameObject, Vector2.up);
        SetupButton(transform.Find("down").gameObject, Vector2.down);
        SetupButton(transform.Find("left").gameObject, Vector2.left);
        SetupButton(transform.Find("right").gameObject, Vector2.right);
    }

    void SetupButton(GameObject buttonObject, Vector2 position)
    {
        EventTrigger eventTrigger = buttonObject.AddComponent<EventTrigger>();

        var pointerDown = new EventTrigger.Entry();
        pointerDown.eventID = EventTriggerType.PointerDown;
        pointerDown.callback.AddListener((e) => UpdateAxisValue(position));
        eventTrigger.triggers.Add(pointerDown);

        var pointerUp = new EventTrigger.Entry();
        pointerUp.eventID = EventTriggerType.PointerUp;
        pointerUp.callback.AddListener((e) => UpdateAxisValue(position, reset: true));
        eventTrigger.triggers.Add(pointerUp);
    }

    void UpdateAxisValue(Vector2 position, bool reset = false)
    {
        if (position.x == 0)
            Vertical = reset ? 0 : position.y;
        else
            Horizontal = reset ? 0 : position.x;
    }
}

TouchMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class TouchMove : MonoBehaviour
{
    public float speed = 5;
    Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float inputH = TouchController.Horizontal;
        float inputV = TouchController.Vertical;
        rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed);
    }
}