- Home /
Question by
SalahChafai160 · Mar 27, 2019 at 04:37 PM ·
mobilejoystick
Mobile Joystick
Hi, Guys That is not a question. a lot of you were asking about how to create a mobile joystick so I wanted to help and there you go that is the joystick script :
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Joystick : MonoBehaviour {
public RectTransform Circle, Center;
Vector2 direction = Vector2.zero;
public bool IsTouching;
float maxLenght;
Touch touch;
int _id;
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (Input.touchCount > 0 && !IsTouching) {
if (Input.GetTouch(Input.touchCount - 1).phase == TouchPhase.Began) {
if (Input.GetTouch(Input.touchCount - 1).position.x < Screen.width / 3 && Input.GetTouch(Input.touchCount - 1).position.y < Screen.height / 2) {
_id = Input.GetTouch(Input.touchCount - 1).fingerId;
touch = GetTouchId (_id);
Circle.transform.position = touch.position;
Center.transform.position = touch.position;
IsTouching = true;
}
}
}
if (IsTouching && Input.touchCount > 0) {
touch = GetTouchId (_id);
maxLenght = ((62.5f * Screen.width / 960) + (62.5f * Screen.height / 540)) / 2;
Center.transform.position = Circle.transform.position + Vector3.ClampMagnitude ((Vector3)touch.position - Circle.transform.position, maxLenght);
direction = Center.transform.position - Circle.transform.position;
}
if (touch.phase == TouchPhase.Ended) {
Circle.anchoredPosition = Vector2.one * 125;
Center.anchoredPosition = Vector2.one * 125;
IsTouching = false;
}
}
public Vector2 GetDirection () {
return direction.normalized;
}
Touch GetTouchId (int id) {
for (int i = 0; i < Input.touchCount; i++) {
if (id == Input.GetTouch (i).fingerId)
return Input.GetTouch (i);
}
return Input.GetTouch (0);
}
}
and if anyone is having a problem with setting up the joystick the pictures below may help. sorry for my bad English and I hope that helped
capture.png
(37.3 kB)
capture1.png
(90.8 kB)
Comment
Your answer
Follow this Question
Related Questions
Make joystick rotate object 0 Answers
Mobile Joystick Problem 2 Answers
Android C# JoyStick Movement 0 Answers
How do i properly use Application.platform ? 1 Answer
Limiting Velocity when using joystick 0 Answers