Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class MoveObject : MonoBehaviour
- {
- private GameObject _target;
- private Ray _ray;
- private bool isMouseDrag;
- private Vector3 screenPosition;
- private Vector3 offset;
- void Update ()
- {
- moveObject ();
- }
- GameObject ReturnClickedObject(out RaycastHit hit)
- {
- _target = null;
- _ray = Camera.main.ScreenPointToRay (Input.mousePosition);
- if (Physics.Raycast (_ray.origin, _ray.direction * 10, out hit))
- {
- _target = hit.collider.gameObject;
- }
- return _target;
- }
- public void moveObject()
- {
- if (Input.GetMouseButtonDown(0))
- {
- RaycastHit hitInfo;
- _target = ReturnClickedObject(out hitInfo);
- if (_target != null)
- {
- isMouseDrag = true;
- Debug.Log("_target position :" + _target.transform.position);
- //Convert world position to screen position.
- screenPosition = Camera.main.WorldToScreenPoint(_target.transform.position);
- offset = _target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
- }
- }
- if (Input.GetMouseButtonUp(0))
- {
- isMouseDrag = false;
- }
- if (isMouseDrag)
- {
- //track mouse position.
- Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
- //convert screen position to world position with offset changes.
- Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
- //It will update _target gameobject's current postion.
- _target.transform.position = currentPosition;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement