1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class DragObject : MonoBehaviour
- {
- private Vector3 mOffset;
- private float mZCoord;
- void OnMouseDown()
- {
- mZCoord = Camera.main.WorldToScreenPoint(
- gameObject.transform.position).z;
- // Store offset = gameobject world pos - mouse world pos
- mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
- }
- private Vector3 GetMouseAsWorldPoint()
- {
- // Pixel coordinates of mouse (x,y)
- Vector3 mousePoint = Input.mousePosition;
- // z coordinate of game object on screen
- mousePoint.z = mZCoord;
- // Convert it to world points
- return Camera.main.ScreenToWorldPoint(mousePoint);
- }
- void OnMouseDrag()
- {
- transform.position = GetMouseAsWorldPoint() + mOffset;
- }
- }
|