Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2014
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Joystick : MonoBehaviour {
  5.  
  6. public bool view = true;
  7.  
  8. public Vector2 output;
  9.  
  10. public Texture2D stick;
  11. public Texture2D back;
  12.  
  13. public GUIStyle stickStyle;
  14. public GUIStyle backStyle;
  15.  
  16. public Vector2 position = new Vector2(0.15f, 0.75f);
  17.  
  18. public float stickSize = 0.175f;
  19. public float backSize = 0.225f;
  20.  
  21. public float activeRadius = 0.2f;
  22.  
  23. public Vector2 input;
  24.  
  25. public bool touched;
  26.  
  27. void Update ()
  28. {
  29. stickStyle.normal.background = stick;
  30. backStyle.normal.background = back;
  31.  
  32. float s = ((Screen.width + Screen.height) / 2) * stickSize;
  33. float b = ((Screen.width + Screen.height) / 2) * backSize;
  34.  
  35. float posX = position.x * Screen.width;
  36. float posY = position.y * Screen.height;
  37.  
  38. if(Application.platform == RuntimePlatform.Android)
  39. {
  40. for(int i = 0;i < Input.touchCount;i++)
  41. {
  42. float x = Input.GetTouch(i).position.x;
  43. float y = Screen.height - Input.GetTouch(i).position.y;
  44.  
  45. if(Vector2.Distance( new Vector2(posX, posY), new Vector2(x, y) ) < (((Screen.width + Screen.height) / 2) * activeRadius))
  46. {
  47. input = new Vector2(x, y);
  48. }
  49. }
  50. }else
  51. input = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
  52.  
  53. if(Input.GetMouseButton(0) || touched)
  54. {
  55. if(Vector2.Distance( new Vector2(posX, posY), input ) < (((Screen.width + Screen.height) / 2) * activeRadius))
  56. {
  57. float x = (input.x - posX) / (b / 2);
  58. float y = -(input.y - posY) / (b / 2);
  59. output = new Vector2(x, y);
  60. }
  61. }else
  62. {
  63. output = Vector2.zero;
  64. }
  65. }
  66.  
  67. void OnGUI ()
  68. {
  69. if(view)
  70. {
  71. float s = ((Screen.width + Screen.height) / 2) * stickSize;
  72. float b = ((Screen.width + Screen.height) / 2) * backSize;
  73.  
  74. float stickX = Screen.width * position.x - s / 2 - Mathf.Clamp(-output.x, -1f, 1f) * (b / 2);
  75. float stickY = Screen.height * position.y - s / 2 - Mathf.Clamp(output.y, -1f, 1f) * (b / 2);
  76.  
  77. GUI.Box ( new Rect(stickX, stickY, s, s), "", stickStyle); // Stick
  78.  
  79. GUI.Box ( new Rect(Screen.width * position.x - b / 2, Screen.height * position.y - b / 2, b, b), "", backStyle); // Back
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement