본문으로 건너뛰기

drag-and-drop

Drag and Drop in Unity

이 글은 기존 블로그의 원문에서 가져왔습니다. 원문 작성일: 2023-03-20

 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class DragAndDrop : MonoBehaviour
{
    public bool isDragging = false;
    Vector3 itemPosition;
    Transform objectTransform;
 
    // Start is called before the first frame update
    void Start()
    {
        objectTransform = gameObject.GetComponent<Transform>();
    }
 
    private void OnMouseDown()
    {
        Debug.Log("DragAndDrop.cs : mouseDown");
        isDragging = true;
    }
 
    private void OnMouseDrag()
    {
        Debug.Log("DragAndDrop.cs : isDragging");
        if (isDragging)
        {
            Vector3 temp = new Vector3(0, 0, 9);
            objectTransform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) + temp;
        }
    }
 
    private void OnMouseUp()
    {
        Debug.Log("DragAndDrop.cs : mouseUp");
        isDragging = false;
    }
}

OnMouseDown(), OnMouseDrag(), OnMouseUp()을 통해 GameObject의 Collider에 마우스 클릭, 드레그 등을 감지할 수 있다. 그렇기에 그것을 이용해서 Drag and Drop을 만들 수 있다.

30 - Input.mousePosition을 통해서 마우스의 위치를 불러 올 수 있다. 하지만 그 좌표를 바로 쓸 수 없기 때문에 좌표를 WorldPoint로 봐꿔주어야한다. 그렇게 하기 위해서 Camera.main.ScreenToWorldPoint()를 이용해서 바꾸어준다. 이때 마우스의 좌표의 z값으로 그 위치로 GameObject를 이동시킨다면 화면에 보이지 않기 때문에 temp를 통해서 z값을 적당하게 옮겨준다.