82 lines
2.8 KiB
C#
82 lines
2.8 KiB
C#
using System.Collections.Generic;
|
|
using Items;
|
|
using Terrain;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
namespace UI {
|
|
public class DragAndDropHandler : MonoBehaviour {
|
|
[SerializeField] private UIItemSlot cursorSlot = null;
|
|
private ItemSlot _cursorItemSlot;
|
|
[SerializeField] private GraphicRaycaster raycaster = null;
|
|
private PointerEventData _pointerEventData;
|
|
[SerializeField] private EventSystem eventSystem = null;
|
|
|
|
private World _world;
|
|
|
|
private void Start() {
|
|
_world = GameObject.Find("World").GetComponent<World>();
|
|
|
|
_cursorItemSlot = new ItemSlot(cursorSlot);
|
|
}
|
|
|
|
|
|
private void Update() {
|
|
if (!_world.MenuOpen) return;
|
|
|
|
cursorSlot.transform.position = Input.mousePosition + new Vector3(-24, 0, 0);
|
|
|
|
if (Input.GetMouseButtonDown(0)) {
|
|
HandleSlotClick(CheckForSlot());
|
|
}
|
|
}
|
|
|
|
private void HandleSlotClick(UIItemSlot clickedSlot) {
|
|
if (clickedSlot == null) return;
|
|
if (!cursorSlot.HasItem && !clickedSlot.HasItem) return;
|
|
|
|
if (clickedSlot.itemSlot.creative) {
|
|
_cursorItemSlot.EmptySlot();
|
|
_cursorItemSlot.InsertStack(clickedSlot.itemSlot.Stack);
|
|
return;
|
|
}
|
|
|
|
if (!cursorSlot.HasItem && clickedSlot.HasItem) {
|
|
_cursorItemSlot.InsertStack(clickedSlot.itemSlot.TakeAll());
|
|
return;
|
|
}
|
|
|
|
if (cursorSlot.HasItem && !clickedSlot.HasItem) {
|
|
clickedSlot.itemSlot.InsertStack(_cursorItemSlot.TakeAll());
|
|
return;
|
|
}
|
|
|
|
if (cursorSlot.HasItem && clickedSlot.HasItem) {
|
|
if (cursorSlot.itemSlot.Stack.Block != clickedSlot.itemSlot.Stack.Block) {
|
|
ItemStack oldCursorSlot = cursorSlot.itemSlot.TakeAll();
|
|
ItemStack oldSlot = clickedSlot.itemSlot.TakeAll();
|
|
|
|
clickedSlot.itemSlot.InsertStack(oldCursorSlot);
|
|
cursorSlot.itemSlot.InsertStack(oldSlot);
|
|
}
|
|
}
|
|
}
|
|
|
|
private UIItemSlot CheckForSlot() {
|
|
_pointerEventData = new PointerEventData(eventSystem);
|
|
_pointerEventData.position = Input.mousePosition;
|
|
|
|
List<RaycastResult> results = new List<RaycastResult>();
|
|
raycaster.Raycast(_pointerEventData, results);
|
|
|
|
foreach (RaycastResult result in results) {
|
|
if (result.gameObject.CompareTag("UIItemSlot")) {
|
|
return result.gameObject.GetComponent<UIItemSlot>();
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
} |