MouseAction.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. public class MouseAction : MonoBehaviour, IPointerEnterHandler, IPointerDownHandler, IPointerUpHandler, IBeginDragHandler, IDragHandler {
  6. // 给定一个参数保存鼠标按下时候的位置
  7. private Vector3 startPos;
  8. // 给定一个参数来保存鼠标移动时候的位置
  9. private Vector3 movePos;
  10. // Use this for initialization
  11. void Start () {
  12. }
  13. // Update is called once per frame
  14. void Update () {
  15. }
  16. /*
  17. * 鼠标进入时候的回调
  18. */
  19. public void OnPointerEnter(PointerEventData eventData) {
  20. print("鼠标进入 ... ");
  21. }
  22. /*
  23. * 鼠标按下时的回调
  24. */
  25. public void OnPointerDown(PointerEventData eventData) {
  26. // 给起始和移动参数保存值
  27. startPos = eventData.position;
  28. movePos = startPos;
  29. }
  30. /*
  31. * 鼠标抬起时的回调
  32. */
  33. public void OnPointerUp(PointerEventData eventData) {
  34. print("鼠标抬起 ... ");
  35. }
  36. public void OnBeginDrag(PointerEventData eventData) {
  37. print("开始拖拽 ... ");
  38. }
  39. /*
  40. * 鼠标拖拽时的回调
  41. */
  42. public void OnDrag(PointerEventData eventData) {
  43. // 首先记录下抬起时候的位置
  44. Vector3 endPos = eventData.position;
  45. // 计算出卡片拖拽时候的位置,由原位置加上最终位置减去移动位置
  46. Vector3 pos = new Vector3(transform.position.x + (endPos.x - movePos.x),
  47. transform.position.y + (endPos.y - movePos.y), 0);
  48. // 赋值给当前组件
  49. transform.position = pos;
  50. // 再更新移动位置
  51. movePos = endPos;
  52. }
  53. }