evershade/Assets/Scripts/Controllers/InventoryItemDisplayControl...

118 lines
3.4 KiB
C#

using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI;
// Drag Dropable
public class InventoryItemDisplayController : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler,
IDragHandler
{
[SerializeField] private Canvas canvas;
[FormerlySerializedAs("InventoryItem")]
public GameItem gameItem;
private CanvasGroup _canvasGroup;
private Canvas _dragLayerCanvas;
private Transform _originalParent;
private Vector2 _originalPosition;
private RectTransform _rectTransform;
private void Awake()
{
_rectTransform = GetComponent<RectTransform>();
_canvasGroup = GetComponent<CanvasGroup>();
if (_canvasGroup == null) _canvasGroup = gameObject.AddComponent<CanvasGroup>();
if (canvas == null) canvas = GameObject.Find("UICanvas").GetComponent<Canvas>();
_dragLayerCanvas = GameObject.Find("DragLayerCanvas").GetComponent<Canvas>();
}
// Update is called once per frame
private void Update()
{
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("Begin Drag");
_originalPosition = _rectTransform.anchoredPosition;
_canvasGroup.alpha = 0.6f;
_canvasGroup.blocksRaycasts = false;
_canvasGroup.interactable = false; // Disable interaction while dragging
}
public void OnDrag(PointerEventData eventData)
{
// Ensure the canvas is set
if (canvas == null)
{
Debug.LogWarning("Canvas is null");
return;
}
// Convert the mouse position to canvas space and update the item's position
Vector2 localPointerPosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
canvas.transform as RectTransform,
eventData.position,
canvas.worldCamera,
out localPointerPosition);
_rectTransform.localPosition = localPointerPosition;
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("End Drag");
// Check if dropped on a valid slot
var hitObjects = eventData.hovered;
var droppedOnValidSlot = false;
foreach (var obj in hitObjects)
if (obj.GetComponent<InventorySlotDisplayController>() != null)
{
droppedOnValidSlot = true;
break;
}
if (!droppedOnValidSlot)
// Snap back to original position if not dropped in a valid slot
_rectTransform.anchoredPosition = _originalPosition;
_canvasGroup.alpha = 1.0f;
_canvasGroup.blocksRaycasts = true;
_canvasGroup.interactable = true; // Enable interaction after dragging
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("OnPointerDown");
}
public void SetItem(GameItem item)
{
if (item == null)
{
Debug.Log("Item is null!");
gameItem = null;
Destroy(transform.gameObject);
return;
}
gameItem = item;
Debug.Log(transform.GetChild(1));
transform.Find("ItemName").GetComponent<TMP_Text>().text = item.itemName;
transform.Find("qty").GetComponent<Text>().text = item.qty;
transform.Find("Icon").GetComponent<Image>().sprite = item.icon;
Debug.Log("completed processing set item");
}
}