Untitled
plain_text
19 days ago
3.3 kB
4
Indexable
Never
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DragDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { private Vector2 originalPosition; private Transform originalParent; public RectTransform rectTransform; private Canvas overlayCanvas; private Camera mainCamera; private CardHoverEffect cardHoverEffect; // Reference to the CardHoverEffect script private HandArea handArea; // Reference to the HandArea script private void Awake() { rectTransform = GetComponent<RectTransform>(); overlayCanvas = GameObject.FindGameObjectWithTag("OverlayCanvas").GetComponent<Canvas>(); mainCamera = Camera.main; cardHoverEffect = GetComponent<CardHoverEffect>(); // Get the CardHoverEffect script handArea = transform.parent.GetComponent<HandArea>(); // Get the HandArea script from the parent object } private bool droppedOnValidZone = false; public void OnDroppedOnValidZone() { droppedOnValidZone = true; } public void OnBeginDrag(PointerEventData eventData) { Debug.Log("Begin dragging: " + gameObject.name); // Store the original parent and position of the object. originalParent = transform.parent; originalPosition = rectTransform.anchoredPosition; // Disable EventTrigger and hover effect while dragging the object. GetComponent<EventTrigger>().enabled = false; if (cardHoverEffect != null) // Check if cardHoverEffect is available { cardHoverEffect.DisableHover(); } // Disable curve updates in HandArea handArea.DisableCurveUpdate(); // Move the object to the top of the UI hierarchy of the overlay canvas so it appears in front of everything else. transform.SetParent(overlayCanvas.transform); } public void OnDrag(PointerEventData eventData) { rectTransform.anchoredPosition += eventData.delta / overlayCanvas.scaleFactor; // Using delta to move with the mouse. } public void OnEndDrag(PointerEventData eventData) { Debug.Log("End dragging: " + gameObject.name + " Dropped on: " + eventData.pointerCurrentRaycast.gameObject.name); // Re-enable EventTrigger and hover effect when the dragging ends. GetComponent<EventTrigger>().enabled = true; if (cardHoverEffect != null) // Check if cardHoverEffect is available { cardHoverEffect.EnableHover(); } // Enable curve updates in HandArea handArea.EnableCurveUpdate(); // Check if the card was dropped on a valid zone if (droppedOnValidZone) { transform.SetParent(eventData.pointerCurrentRaycast.gameObject.transform); rectTransform.anchoredPosition = Vector2.zero; // Set position in the center of the drop zone. droppedOnValidZone = false; // Reset the flag } else { // If not, revert to its original parent and position. transform.SetParent(originalParent); rectTransform.anchoredPosition = originalPosition; } } }