当前位置:   article > 正文

unity--拖拽(UI-Image 、Sprite Render)_unity ui拖拽

unity ui拖拽

目录

1.UI ---Image拖拽

2.sprite Renderer拖拽



1.UI ---Image拖拽

控制脚本需继承IBeginDragHandler, IEndDragHandler, IDragHandler 三个接口 并实现接口方法

⚠️注意:添加Coliider 2D碰撞体

  1. public class ItemContr : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
  2. {
  3. private RectTransform rectTrans;
  4. private void Awake()
  5. {
  6. rectTrans = GetComponent<RectTransform>();
  7. }
  8. private void OnTriggerEnter2D(Collider2D other)
  9. {
  10. //....
  11. }
  12. private void OnTriggerExit2D(Collider2D other)
  13. {
  14. //....
  15. }
  16. public void OnBeginDrag(PointerEventData eventData)
  17. {
  18. rectTrans.SetAsLastSibling();
  19. }
  20. public void OnDrag(PointerEventData eventData)
  21. {
  22. rectTrans.anchoredPosition += eventData.delta;
  23. }
  24. public void OnEndDrag(PointerEventData eventData)
  25. {
  26. rectTrans.SetSiblingIndex(1);
  27. }
  28. }

2.sprite Renderer拖拽

⚠️注意:

1.添加Collider2D 碰撞体

2.Camera的Projection 需设置为Orthographic模式

  1. using UnityEngine;
  2. public class ItemContr : MonoBehaviour
  3. {
  4. private Camera _camera;
  5. private void Awake()
  6. {
  7. _camera = GameObject.FindGameObjectWithTag("camera").GetComponent<Camera>();
  8. }
  9. void Start()
  10. {
  11. }
  12. void Update()
  13. {
  14. }
  15. private void OnMouseDown()
  16. {
  17. //Debug.LogError("down");
  18. }
  19. private void OnMouseDrag()
  20. {
  21. if (_camera == null)
  22. {
  23. return;
  24. }
  25. //leftMax -2.7 rightMax 2.9 topMax 1.77 downMax -1.25
  26. var offsetX = _camera.ScreenToWorldPoint(Input.mousePosition).x;
  27. var offsetY = _camera.ScreenToWorldPoint(Input.mousePosition).y;
  28. transform.position = new Vector3(Mathf.Clamp(offsetX, -2.7f, 2.9f), Mathf.Clamp(offsetY, -1.25f, 1.77f), 0);
  29. }
  30. private void OnMouseUp()
  31. {
  32. //Debug.LogError("Up");
  33. }
  34. private void OnTriggerEnter2D(Collider2D collision)
  35. {
  36. //Debug.LogError("11111");
  37. }
  38. private void OnTriggerExit2D(Collider2D collision)
  39. {
  40. //Debug.LogError("2222");
  41. }
  42. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/106583
推荐阅读
相关标签
  

闽ICP备14008679号