using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems; public class MoveDirections : MonoBehaviour { //控制四个方向的按钮 public GameObject MoveUp; public GameObject MoveDown; public GameObject MoveLeft; public GameObject MoveRight; public GameObject DragRotateBtn; //控制方向的布尔变量 private bool isUp = false; private bool isDown = false; private bool isLeft = false; private bool isRight = false; public Camera UICamera; Vector3 scenePos; Vector3 mous; Vector3 tranScreenPos; Vector3 TempMouse; void Start() { EventTriggerListener.Get(gameObject).onDrag = OnMouseDragUI; EventTriggerListener.Get(DragRotateBtn).onDrag = OnMouseDragUI; EventTriggerListener.Get(gameObject).onDown = OnGameOnDown; EventTriggerListener.Get(DragRotateBtn).onDown = OnGameOnDown; EventTriggerListener.Get(MoveLeft).onDown += OnDownBtnClick; EventTriggerListener.Get(MoveRight).onDown += OnDownBtnClick; EventTriggerListener.Get(MoveDown).onDown += OnDownBtnClick; EventTriggerListener.Get(MoveUp).onDown += OnDownBtnClick; EventTriggerListener.Get(MoveLeft).onUp += OnUpBtnClick; EventTriggerListener.Get(MoveRight).onUp += OnUpBtnClick; EventTriggerListener.Get(MoveDown).onUp += OnUpBtnClick; EventTriggerListener.Get(MoveUp).onUp += OnUpBtnClick; } void Update() { if (isLeft && Input.GetMouseButton(0)) { Debug.Log("向左移动"); } if (isRight && Input.GetMouseButton(0)) { Debug.Log("向右移动"); } if (isUp && Input.GetMouseButton(0)) { Debug.Log("向上移动"); } if (isDown && Input.GetMouseButton(0)) { Debug.Log("向下移动"); } } /// <summary> /// 按下鼠标时判断按下的按钮 /// </summary> /// <param name="btn"></param> void OnDownBtnClick(GameObject btn) { isLeft = (btn == MoveLeft); isRight = (btn == MoveRight); isUp = (btn == MoveUp); isDown = (btn == MoveDown); } void OnGameOnDown(GameObject ga) { mous = Input.mousePosition;//记录下鼠标坐标 tranScreenPos = UICamera.WorldToScreenPoint(transform.position); } /// <summary> /// 鼠标抬起控制方向变量重新设置为false; /// </summary> /// <param name="game"></param> void OnUpBtnClick(GameObject game) { isLeft = false; isRight = false; isUp = false; isDown = false; } /// <summary> /// 点击方向按钮 /// </summary> /// <param name="btn"></param> void OnMouseDragUI(GameObject btn) { TempMouse = mous - Input.mousePosition; scenePos = new Vector3(tranScreenPos.x - TempMouse.x, tranScreenPos.y - TempMouse.y, tranScreenPos.z); transform.position = UICamera.ScreenToWorldPoint(scenePos); } }