Skip to content

Instantly share code, notes, and snippets.

@Nordaj
Last active April 10, 2018 02:20
Show Gist options
  • Save Nordaj/bb2b37408f58706676aad853a37e2be4 to your computer and use it in GitHub Desktop.
Save Nordaj/bb2b37408f58706676aad853a37e2be4 to your computer and use it in GitHub Desktop.
Simple joystick script for mobile use. Dynamic position joystick and has a public member "value"(v2) to store the input value. To use: Create image for the outer circle as a UI object. Create child image for the inner circle. Slap the script on your parent image and you're good to go.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Joystick : MonoBehaviour
{
//Public Variables
public Image centerImg;
[Tooltip("This field does not need to be filled")]
public Text debugText;
public float radius = 50;
public float fadeSpeed = 2;
[HideInInspector]
public Vector2 value;
//Private Varaibles
private RectTransform center;
private RectTransform rt;
private Image img;
private float stAlpha;
private float stCenterAlpha;
private bool isDebug;
void Start()
{
//Get components
rt = GetComponent<RectTransform>();
center = centerImg.GetComponent<RectTransform>();
img = GetComponent<Image>();
//Record stating alphas
stAlpha = img.color.a;
stCenterAlpha = centerImg.color.a;
//Check if debugging
if (debugText != null)
isDebug = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//Set entire joystick pos
rt.position = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
//Reset value
value = Vector2.zero;
//Debug
if (isDebug)
debugText.text = "(" + value.x + ", " + value.y + ")";
}
if (Input.GetMouseButton(0))
{
//Move small joystick
Vector2 pos = ToV2(rt.position) - ToV2(Input.mousePosition);
pos = Vector2.ClampMagnitude(pos, radius);
center.position = ToV2(rt.position) - pos;
//Calculate the value
value = -(pos / radius);
//Debug
if (isDebug)
debugText.text = "(" + value.x + ", " + value.y + ")";
//Fade in
if (img.color.a < stAlpha)
img.color = Fade(img.color, fadeSpeed * Time.deltaTime);
if (centerImg.color.a < stCenterAlpha)
centerImg.color = Fade(centerImg.color, fadeSpeed * Time.deltaTime);
}
else
{
//Fade out
if (img.color.a > 0)
img.color = Fade(img.color, -fadeSpeed * Time.deltaTime);
if (centerImg.color.a > 0)
centerImg.color = Fade(centerImg.color, -fadeSpeed * Time.deltaTime);
}
}
Vector2 ToV2(Vector3 v3)
{
return new Vector2(v3.x, v3.y);
}
Color Fade(Color color, float amount)
{
return new Color(color.r, color.g, color.b, color.a + amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment