Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class Joystick : MonoBehaviour {
- public bool view = true;
- public Vector2 output;
- public Texture2D stick;
- public Texture2D back;
- public GUIStyle stickStyle;
- public GUIStyle backStyle;
- public Vector2 position = new Vector2(0.15f, 0.75f);
- public float stickSize = 0.175f;
- public float backSize = 0.225f;
- public float activeRadius = 0.2f;
- public Vector2 input;
- public bool touched;
- void Update ()
- {
- stickStyle.normal.background = stick;
- backStyle.normal.background = back;
- float s = ((Screen.width + Screen.height) / 2) * stickSize;
- float b = ((Screen.width + Screen.height) / 2) * backSize;
- float posX = position.x * Screen.width;
- float posY = position.y * Screen.height;
- if(Application.platform == RuntimePlatform.Android)
- {
- for(int i = 0;i < Input.touchCount;i++)
- {
- float x = Input.GetTouch(i).position.x;
- float y = Screen.height - Input.GetTouch(i).position.y;
- if(Vector2.Distance( new Vector2(posX, posY), new Vector2(x, y) ) < (((Screen.width + Screen.height) / 2) * activeRadius))
- {
- input = new Vector2(x, y);
- }
- }
- }else
- input = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
- if(Input.GetMouseButton(0) || touched)
- {
- if(Vector2.Distance( new Vector2(posX, posY), input ) < (((Screen.width + Screen.height) / 2) * activeRadius))
- {
- float x = (input.x - posX) / (b / 2);
- float y = -(input.y - posY) / (b / 2);
- output = new Vector2(x, y);
- }
- }else
- {
- output = Vector2.zero;
- }
- }
- void OnGUI ()
- {
- if(view)
- {
- float s = ((Screen.width + Screen.height) / 2) * stickSize;
- float b = ((Screen.width + Screen.height) / 2) * backSize;
- float stickX = Screen.width * position.x - s / 2 - Mathf.Clamp(-output.x, -1f, 1f) * (b / 2);
- float stickY = Screen.height * position.y - s / 2 - Mathf.Clamp(output.y, -1f, 1f) * (b / 2);
- GUI.Box ( new Rect(Screen.width * position.x - b / 2, Screen.height * position.y - b / 2, b, b), "", backStyle); // Back
- GUI.Box ( new Rect(stickX, stickY, s, s), "", stickStyle); // Stick
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement