Forum

User posts wacoha7200
18 January 2023 16:09 [ON MODERATION]
Hello,

I'm not a programmer, but I do some searches and got this from experts. Maybe this will solve your issue

using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;

public class JoystickControl : MonoBehaviour, IDragHandler, IEndDragHandler, IPointerDownHandler, IPointerUpHandler {

private enum AxisOption {HorizontalAndVertical, Horizontal, Vertical}
private enum ControlMode {AnalogStick, DirectionalPad}
private enum ProjectMode {Project3D, Project2D};
[SerializeField] private AxisOption axes;
[SerializeField] private ControlMode mode;
[SerializeField] private ProjectMode project;
public static Vector3 direction { get; private set; }

void Awake()
{
direction = Vector3.zero;
}

Vector2 Round(Vector2 val)
{
float x = Mathf.Abs(val.x);
float y = Mathf.Abs(val.y);

if(x >= 0.5f && y >= 0.5f)
{
val.x = Mathf.Sign(val.x);
val.y = Mathf.Sign(val.y);
return val;
}

if(x > y)
{
val.x = Mathf.Sign(val.x);
val.y = 0;
}
else
{
val.x = 0;
val.y = Mathf.Sign(val.y);
}

return val;
}

void UpdateDirection()
{
Vector2 curDir = new Vector2(Input.touches[0].position.x - transform.position.x, Input.touches[0].position.y - transform.position.y).normalized;
if(mode == ControlMode.DirectionalPad) curDir = Round(curDir);
if(axes == AxisOption.Horizontal) curDir = new Vector2(Mathf.Sign(curDir.x), 0);
else if(axes == AxisOption.Vertical) curDir = new Vector2(0, Mathf.Sign(curDir.y));
if(project == ProjectMode.Project3D) direction = new Vector3(curDir.x, 0, curDir.y); else direction = new Vector3(curDir.x, curDir.y, 0);
}

public void OnPointerDown(PointerEventData eventData)
{
UpdateDirection();
}

public void ondrag(PointerEventData eventData)
{
UpdateDirection();
}

public void OnEndDrag(PointerEventData eventData)
{
direction = Vector3.zero;
}

public void OnPointerUp(PointerEventData eventData)
{
direction = Vector3.zero;
}
}

*>Bringing life to brands with creative logo designs and digital marketing strategies<*