Unity

Drag and Drop in Unity

YunSeong 2023. 3. 20. 17:05
728x90
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
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(009);
            objectTransform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) + temp;
        }
    }
 
    private void OnMouseUp()
    {
        Debug.Log("DragAndDrop.cs : mouseUp");
        isDragging = false;
    }
}
cs

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

 

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

 

728x90
반응형