Advertisement
CakeMeister

3Dball joystick controller

Aug 8th, 2017
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.73 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine.UI;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine;
  6.  
  7. public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
  8. {
  9.     public Image BGimg, joystickIMG;
  10.  
  11.     public Vector3 direction;
  12.     // Use this for initialization
  13.     void Start () {
  14.         BGimg = GetComponent<Image>();
  15.         joystickIMG = transform.GetChild(0).GetComponentInChildren<Image>();
  16.         direction = Vector3.zero;
  17.     }
  18.  
  19.     public void OnDrag(PointerEventData ped)
  20.     {
  21.         Vector2 pos = Vector2.zero;
  22.         if(RectTransformUtility.ScreenPointToLocalPointInRectangle(
  23.             BGimg.rectTransform, ped.position,
  24.             ped.pressEventCamera, out pos))
  25.         {
  26.             pos.x = (pos.x / BGimg.rectTransform.sizeDelta.x);
  27.             pos.y = (pos.y / BGimg.rectTransform.sizeDelta.y);
  28.  
  29.             float x = (BGimg.rectTransform.pivot.x == 1) ? pos.x * 2 + 1 : pos.x * 2 - 1;
  30.             float y = (BGimg.rectTransform.pivot.y == 1) ? pos.y * 2 + 1 : pos.y * 2 - 1;
  31.  
  32.             direction = new Vector3(x, 0, y);
  33.             direction = (direction.magnitude > 1) ? direction.normalized : direction;
  34.  
  35.             joystickIMG.rectTransform.anchoredPosition =
  36.                 new Vector2(direction.x * (BGimg.rectTransform.sizeDelta.x / 3),
  37.                 direction.z * (BGimg.rectTransform.sizeDelta.y / 3));
  38.  
  39.  
  40.             Debug.Log(direction);
  41.         }
  42.            
  43.     }
  44.  
  45.     public void OnPointerDown(PointerEventData ped)
  46.     {
  47.         OnDrag(ped);
  48.     }
  49.  
  50.     public void OnPointerUp(PointerEventData ped)
  51.     {
  52.         direction = Vector3.zero;
  53.         joystickIMG.rectTransform.anchoredPosition = Vector3.zero;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement