核心代码:
using UnityEngine; using System.Collections; using UnityEngine.UI; public delegate void JoystickMoveDelegate(JoystickData data); public class Joystick : MonoBehaviour { public GameObject joystickUI; //摇杆整体UI,方便Active public RectTransform joystickCenter; //摇杆重心 public RectTransform joystickBackground; //摇杆背景 private float halfScreenWidth; private float halfScreenHeight; private RectTransform joystickRect; private float radius; private Vector3 lastMousePosition; public static event JoystickMoveDelegate JoystickMoveEvent; // Use this for initialization void Start () { halfScreenWidth = Screen.width / 2; halfScreenHeight = Screen.height / 2; joystickRect = this.gameObject.GetComponent<RectTransform>(); radius = 71; } // Update is called once per frame void Update () { JoystickController(); } public void JoystickController() { //鼠标一直按下 if (Input.GetMouseButton(0)) { float distance = Vector2.Distance(new Vector2(Input.mousePosition.x, Input.mousePosition.y), joystickRect.anchoredPosition); if (distance < radius) { //当距离小于半径就开始移动 摇杆重心 joystickCenter.anchoredPosition = new Vector2(Input.mousePosition.x - joystickRect.anchoredPosition.x, Input.mousePosition.y - joystickRect.anchoredPosition.y); } else { //求圆上的一点:(目标点-原点) * 半径/原点到目标点的距离 Vector2 endPosition = (new Vector2(Input.mousePosition.x, Input.mousePosition.y) - joystickRect.anchoredPosition) * radius / distance; joystickCenter.anchoredPosition = endPosition; } if (JoystickMoveEvent != null) { JoystickMoveEvent(new JoystickData() { x = joystickCenter.anchoredPosition.x - joystickBackground.anchoredPosition.x, y = joystickCenter.anchoredPosition.y - joystickBackground.anchoredPosition.y }); } } //鼠标按下 if (Input.GetMouseButtonDown(0)) { this.joystickUI.SetActive(true); //鼠标单击左边屏幕 if (Input.mousePosition.x < halfScreenWidth) { joystickRect.anchoredPosition = Input.mousePosition; } //鼠标单击右边屏幕 if (Input.mousePosition.x >= halfScreenWidth) { // Debug.Log("鼠标单击右边"); } } //鼠标释放的时候 if (Input.GetMouseButtonUp(0)) { this.joystickUI.SetActive(false); } } } public class JoystickData { public float x; public float y; }
效果图:
Unity5.1版本:
实例下载地址: http://yunpan.cn/cchdURtqCWXxv 访问密码 0aba
时间: 2024-11-05 13:26:13