IAFahim
Jul 30th, 2024 (edited)
24
0
Never
This is comment for paste Untitled
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using UnityEngine;
  2.  
  3. public class Drag_Drop : MonoBehaviour
  4. {
  5.     public bool isDragging = false;
  6.     public Vector2 offset;
  7.     public Vector2 startPosition;
  8.     public Camera cam;
  9.    
  10.     public GameObject playerdropZone;
  11.     public bool isOverplayerdropZone = false;
  12.     public bool dropInOther = true;
  13.  
  14.  
  15.     private void Start()
  16.     {
  17.         startPosition = transform.position;
  18.     }
  19.  
  20.     private void OnMouseDown()
  21.     {
  22.         isDragging = true;
  23.         offset = GetMousePos() - (Vector2)transform.position;
  24.     }
  25.  
  26.     private void OnMouseDrag()
  27.     {
  28.         Vector2 targetPos = GetMousePos() - offset;
  29.         transform.position = targetPos;
  30.     }
  31.  
  32.     private void OnMouseUp()
  33.     {
  34.         isDragging = false;
  35.     }
  36.  
  37.     private void OnTriggerEnter2D(Collider2D other)
  38.     {
  39.         playerdropZone = other.gameObject;
  40.         isOverplayerdropZone = true;
  41.     }
  42.  
  43.     private void OnTriggerExit2D(Collider2D other)
  44.     {
  45.         isOverplayerdropZone = false;
  46.         playerdropZone = null;
  47.     }
  48.    
  49.  
  50.     private void Update()
  51.     {
  52.         if (isDragging)
  53.         {
  54.             if (isOverplayerdropZone)
  55.             {
  56.                 transform.SetParent(playerdropZone.transform,false);
  57.                 transform.localPosition = Vector3.zero;
  58.             }    
  59.         }
  60.         else
  61.         {
  62.             if (!dropInOther)
  63.             {
  64.                 transform.SetParent(null);
  65.                 transform.position = startPosition;    
  66.             }
  67.         }
  68.     }
  69.  
  70.     private Vector2 GetMousePos()
  71.     {
  72.         var flippedCamZ = -cam.transform.position.z;
  73.         return cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, flippedCamZ));
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment