Advertisement
Guest User

MoveObject

a guest
Oct 21st, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.62 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MoveObject : MonoBehaviour
  5. {
  6.  
  7.     private GameObject _target;
  8.  
  9.     private Ray _ray;
  10.     private bool isMouseDrag;
  11.     private Vector3 screenPosition;
  12.     private Vector3 offset;
  13.  
  14.  
  15.     void Update ()
  16.     {
  17.         moveObject ();
  18.     }
  19.  
  20.     GameObject ReturnClickedObject(out RaycastHit hit)
  21.     {
  22.         _target = null;
  23.  
  24.         _ray = Camera.main.ScreenPointToRay (Input.mousePosition);
  25.  
  26.         if (Physics.Raycast (_ray.origin, _ray.direction * 10, out hit))
  27.         {
  28.             _target = hit.collider.gameObject;
  29.         }
  30.         return _target;
  31.     }
  32.  
  33.     public void moveObject()
  34.     {
  35.         if (Input.GetMouseButtonDown(0))
  36.         {
  37.             RaycastHit hitInfo;
  38.             _target = ReturnClickedObject(out hitInfo);
  39.  
  40.             if (_target != null)
  41.             {
  42.                 isMouseDrag = true;
  43.                 Debug.Log("_target position :" + _target.transform.position);
  44.  
  45.                 //Convert world position to screen position.
  46.                 screenPosition = Camera.main.WorldToScreenPoint(_target.transform.position);
  47.                 offset = _target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
  48.             }
  49.         }
  50.  
  51.         if (Input.GetMouseButtonUp(0))
  52.         {
  53.             isMouseDrag = false;
  54.         }
  55.  
  56.         if (isMouseDrag)
  57.         {
  58.             //track mouse position.
  59.             Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
  60.  
  61.             //convert screen position to world position with offset changes.
  62.             Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
  63.  
  64.             //It will update _target gameobject's current postion.
  65.             _target.transform.position = currentPosition;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement