반응형
SMALL
드래그앤 드롭 인벤토리 구현
IBeginDragHandler, IDragHandler, IEndDragHandler 인터페이스를 상속받아 각각의 기능을 이용해 인벤토리 창의 아이템을 클릭시 (터치시) 해당 아이템을 끌고 다닐수 있게 하였고 인벤토리 범위를 벗어난다면 실제 월드 상에 오브젝트를 생성시키는 스크립트를 구현하였다.
처음 본 메서드는 아래와 같다.
RectTransformUtility.RectangleContainsScreenPoint : 이벤트 발생시 오브젝트의 위치가 특정 오브젝트의 위치를 벗어났는지 체크한다.
위 메서드를 이용해 특정 범위를 따로 지정해주지 않아도 아이템이 인벤토리를 벗어났는지 않았는지 등을 체크 가능하다.
일단 1단계는 만들었으니 다음 구현 목표는 아래와 같다.
- 플레이어가 아이템과 접촉시 액션을 이용해 해당 아이템의 이름을 보내고 아이템 아이콘 제너레이터 에게 해당 아이콘을 인벤토리칸에 넣어주게 한다.
- 스탯 창을 특정 버튼을 눌러 확장시켜 보여준다.
일단 구현은 어렵지 않지만 구조를 어떤식으로 해야할지는 다른 얘기인지라 좀더 구조를 신경쓰며 만들어봐야겠다.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UIElements;
public class UIInventory : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
private Vector2 itemPos;
[SerializeField]
private GameObject item;
void Awake()
{
this.rectTransform = GetComponent<RectTransform>();
this.canvasGroup = GetComponent<CanvasGroup>();
this.itemPos = this.rectTransform.localPosition;
}
public void OnBeginDrag(PointerEventData eventData)
{
//드래그를 시작할시
this.canvasGroup.alpha = .6f;
this.canvasGroup.blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
//드래그 하는 동안
this.rectTransform.anchoredPosition += eventData.delta;
}
public void OnEndDrag(PointerEventData eventData)
{
//드래그를 끝냈을때
this.canvasGroup.alpha = 1f;
this.canvasGroup.blocksRaycasts = true;
// 드래그를 끝낸 위치가 지정된 오브젝트의 범위를 벗어났는지 체크한다
if (!RectTransformUtility.RectangleContainsScreenPoint(this.rectTransform.parent.parent.parent.GetComponent<RectTransform>(),this.rectTransform.position))
{
//out 매개변수로 받은 월드포지션
Vector3 worldPos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(this.rectTransform.parent.GetComponent<RectTransform>(), this.rectTransform.position, Camera.main, out worldPos))
{
//해당 오브젝트를 월드 좌표에 생성
GameObject item = Instantiate(this.item, worldPos, Quaternion.identity);
//인벤토리 오브젝트 삭제
Destroy(this.gameObject);
}
}
else
{
//만약 범위를 벗어나지 않았다면 위치 초기화
this.rectTransform.localPosition = this.itemPos;
}
}
}
반응형
LIST
'프로젝트 > 건즈앤 레이첼스' 카테고리의 다른 글
[유니티 프로젝트] 옵션 UI .2 (1) | 2023.04.02 |
---|---|
[유니티 프로젝트] 옵션 UI (0) | 2023.04.01 |
[랜덤 맵 생성] A* 알고리즘을 이용한 절차적 맵 제작 방법 정리 (0) | 2023.03.30 |
[유니티 프로젝트] 랜덤맵 + 플레이어 조작 합치기 (0) | 2023.03.28 |
[유니티 프로젝트] 맵 텔레포트 카메라 이동 및 맵 외곽의 void 만들기 (0) | 2023.03.26 |