Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- using UnityEngine;
- public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
- {
- public Image BGimg, joystickIMG;
- public Vector3 direction;
- // Use this for initialization
- void Start () {
- BGimg = GetComponent<Image>();
- joystickIMG = transform.GetChild(0).GetComponentInChildren<Image>();
- direction = Vector3.zero;
- }
- public void OnDrag(PointerEventData ped)
- {
- Vector2 pos = Vector2.zero;
- if(RectTransformUtility.ScreenPointToLocalPointInRectangle(
- BGimg.rectTransform, ped.position,
- ped.pressEventCamera, out pos))
- {
- pos.x = (pos.x / BGimg.rectTransform.sizeDelta.x);
- pos.y = (pos.y / BGimg.rectTransform.sizeDelta.y);
- float x = (BGimg.rectTransform.pivot.x == 1) ? pos.x * 2 + 1 : pos.x * 2 - 1;
- float y = (BGimg.rectTransform.pivot.y == 1) ? pos.y * 2 + 1 : pos.y * 2 - 1;
- direction = new Vector3(x, 0, y);
- direction = (direction.magnitude > 1) ? direction.normalized : direction;
- joystickIMG.rectTransform.anchoredPosition =
- new Vector2(direction.x * (BGimg.rectTransform.sizeDelta.x / 3),
- direction.z * (BGimg.rectTransform.sizeDelta.y / 3));
- Debug.Log(direction);
- }
- }
- public void OnPointerDown(PointerEventData ped)
- {
- OnDrag(ped);
- }
- public void OnPointerUp(PointerEventData ped)
- {
- direction = Vector3.zero;
- joystickIMG.rectTransform.anchoredPosition = Vector3.zero;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement