DragObject.cs 919 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class DragObject : MonoBehaviour
  5. {
  6. private Vector3 mOffset;
  7. private float mZCoord;
  8. void OnMouseDown()
  9. {
  10. mZCoord = Camera.main.WorldToScreenPoint(
  11. gameObject.transform.position).z;
  12. // Store offset = gameobject world pos - mouse world pos
  13. mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
  14. }
  15. private Vector3 GetMouseAsWorldPoint()
  16. {
  17. // Pixel coordinates of mouse (x,y)
  18. Vector3 mousePoint = Input.mousePosition;
  19. // z coordinate of game object on screen
  20. mousePoint.z = mZCoord;
  21. // Convert it to world points
  22. return Camera.main.ScreenToWorldPoint(mousePoint);
  23. }
  24. void OnMouseDrag()
  25. {
  26. transform.position = GetMouseAsWorldPoint() + mOffset;
  27. }
  28. }