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


JoystickController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
 
public class JoystickController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [SerializeField]
    private float maxDisplacement = 200;
    Vector2 startPos;
    Transform handle;
 
    public static float Horizontal = 0, Vertical = 0;
 
    void Start()
    {
        handle = transform.GetChild(0);
        startPos = handle.position;
    }
 
    void UpdateHandlePosition(Vector2 pos)
    {
        var delta = pos - startPos;
        delta = Vector2.ClampMagnitude(delta, maxDisplacement);
        handle.position = startPos + delta;
        Horizontal = delta.x / maxDisplacement;
        Vertical = delta.y / maxDisplacement;
    }
 
    public void OnPointerDown(PointerEventData eventData)
    {
        UpdateHandlePosition(eventData.position);
    }
 
    public void OnDrag(PointerEventData eventData)
    {
        UpdateHandlePosition(eventData.position);
    }
 
    public void OnPointerUp(PointerEventData eventData)
    {
        UpdateHandlePosition(startPos);
    }
}

JoystickMove.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
[RequireComponent(typeof(Rigidbody))]
public class JoystickMove : MonoBehaviour
{
    public float speed = 5;
    Rigidbody rigidBody;
 
    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }
 
    void FixedUpdate()
    {
        float inputH = JoystickController.Horizontal;
        float inputV = JoystickController.Vertical;
        rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed);
    }
}