TTTObjectDrag.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace ToneTuneToolkit
  4. {
  5. /// <summary>
  6. /// OK
  7. /// 对象拖拽
  8. /// 挂在需要拖拽的对象上
  9. /// 需要相机为MainCameraTag
  10. /// 需要碰撞器
  11. /// </summary>
  12. public class TTTObjectDrag : MonoBehaviour
  13. {
  14. private Vector3 screenPosition;
  15. private Vector3 offset;
  16. private Vector3 currentScreenPosition;
  17. private void Start()
  18. {
  19. if (!Camera.main)
  20. {
  21. TTTTipTools.Notice(this.name + "相机缺失");
  22. this.enabled = false;
  23. return;
  24. }
  25. }
  26. private IEnumerator OnMouseDown()
  27. {
  28. screenPosition = Camera.main.WorldToScreenPoint(gameObject.transform.position);
  29. offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
  30. while (Input.GetMouseButton(0) || Input.GetMouseButton(1))
  31. {
  32. currentScreenPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
  33. gameObject.transform.position = Camera.main.ScreenToWorldPoint(currentScreenPosition) + offset;
  34. yield return new WaitForFixedUpdate();
  35. }
  36. }
  37. }
  38. }