- Home /
mobile joystick
hi, guys that is not a question it is the answer for the known question: How to create a mobile joystick so yeah that is the 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;
Debug.Log ("finger id : " + _id);
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);
}
}
sorry for my bad English and hope that helped.
Answer by Draxgter1001 · Aug 17, 2020 at 07:42 PM
@SalahChafai160 Can I use this to make my player shoot, based on the direction I'm pointing with the Joystick?
Your answer
Follow this Question
Related Questions
how to rotate object with joystick (Mobile) 0 Answers
If mobile joystick is moved , then animation transforms from idle to walk? 2 Answers
Character Controller Initial Problem With Mobile 0 Answers
Mobile joystick is not working in unity 2018.1 only jump button works 0 Answers
How do I make the center of the joystick bounce back to the middle when its not being used?, 0 Answers