FarmRPG　Unity Inventory&Item Part7 1/2 インベントリのアイテムをドラッグ　ドラッグ中アイテムがマウスが追従する

# 概要
今回は
インベントリのアイテムをドラッグしたらアイテムオブジェクトを作成し、
ドラッグ中はそのオブジェクトがマウスに追従するようにします。

![0602.gif](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/c9f03d10-9be6-5092-18bf-1b973af3c6f1.gif)



# 開発環境

IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10

# UnityEditor上の設定

## inventoryBarDraggedItem ドラッグ中にマウスに追従するアイテムプレハブ


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/3999a2eb-d578-9124-bcbf-8ad4dc51c6f6.png)


## UIInventoryBarの引数を指定
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/9b8be9a1-3eaf-dae9-12e5-f57b24790105.png)


# 実装のポイント

## ドラッグ開始時の処理 OnBeginDragメソッド

UIInventorySlotにOnBeignDragメソッドを追加します。
ドラッグ開始中はPlayerが動かないように　PlayerクラスのUpdateメソッドを修正します。


![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/fe6e8f28-b891-4b26-9eac-56de4ca50931.png)


## ドラッグ中の処理 OnDragメソッド

OnBeginDragメソッドで作成したdraggedItemをマウスカーソルに追従するようにします。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/33559ecd-04c7-c60d-e142-31c121dbae16.png)


# コード部分

## Player

```diff_c_sharp:Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : SingletonMonobehaviour<Player>
{
    // Movement Parameters
    private float xInput;
    private float yInput;
    private bool isIdle;
    private bool isRunning;
    private bool isWalking;

    private Rigidbody2D rigidBody2D;
    private float movementSpeed;

+    private bool _playerInputIsDisabled = false;
+    public bool PlayerInputIsDisabled { get => _playerInputIsDisabled; set => _playerInputIsDisabled = value; }

    protected override void Awake()
    {
        base.Awake();
        rigidBody2D = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
+        if (!PlayerInputIsDisabled)
+        {

            PlayerMovementInput();
            PlayerWalkInput();

            EventHandler.CallMovementEvent(xInput, yInput, isWalking, isRunning, isIdle, isCarrying, toolEffect,
                isUsingToolRight, isUsingToolLeft, isUsingToolUp, isUsingToolDown,
                isLiftingToolRight, isLiftingToolLeft, isLiftingToolUp, isLiftingToolDown,
                isPickingRight, isPickingLeft, isPickingUp, isPickingDown,
                isSwingingToolRight, isSwingingToolLeft, isSwingingToolUp, isSwingingToolDown,
                false, false, false, false);
+        }
    }

    private void FixedUpdate()
    {
        PlayerMovement();
    }
    private void PlayerMovement(){}    
    private void PlayerMovementInput(){}
    private void PlayerWalkInput(){}

+    private void ResetMovement()
+    {
+        xInput = 0f;
+        yInput = 0f;
+        isRunning = false;
+        isWalking = false;
+        isIdle = true;
+    }
+    public void DisablePlayerInputAndResetMovement()
+    {
+        DisablePlayerInput();
+        ResetMovement();
+    }

+    private void DisablePlayerInput()
+    {
+        PlayerInputIsDisabled = true;
+    }
    
    
    
    
    
}


```


## UIInventoryBar

```diff_c_sharp:UIInventoryBar.cs
using System.Collections.Generic;
using UnityEngine;


public class UIInventoryBar : MonoBehaviour
{
    [SerializeField] private Sprite blank16x16sprite = null;
    [SerializeField] private UIInventorySlot[] inventorySlot = null;
+    public GameObject inventoryBarDraggedItem;
    
    private void OnDisable(){}
    private void OnEnable(){}

    private void ClearInventorySlots(){}
    private void InventoryUpdated(InventoryLocation inventoryLocation, List<InventoryItem> inventoryList){}
   
}


```

## UIInventorySlot

```diff_c_sharp:UIInventorySlot.cs

using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIInventorySlot : MonoBehaviour,IBeginDragHandler,IDragHandler
{
+    private GameObject draggedItem;
    
    public Image inventorySlotHighlight;
    public Image inventorySlotImage;
    public TextMeshProUGUI textMeshProUGUI;
+    [SerializeField] private UIInventoryBar inventoryBar = null;
    public ItemDetails itemDetails;
    public int itemQuantity;

+    public void OnBeginDrag(PointerEventData eventData)
+    {
+        if (itemDetails != null)
+        {
+            Player.Instance.DisablePlayerInputAndResetMovement();
+            draggedItem = Instantiate(inventoryBar.inventoryBarDraggedItem, inventoryBar.transform);

+            Image draggedItemImage = draggedItem.GetComponentInChildren<Image>();
+            draggedItemImage.sprite = inventorySlotImage.sprite;
+        }
+    }

+    public void OnDrag(PointerEventData eventData)
+    {
+        if (draggedItem != null)
+        {
+            draggedItem.transform.position = Input.mousePosition;
+        }
+    }

}

```






# 参考

## C#

## Unity Editor コンポーネント

## Unity スクリプト

### OnBeginDrag

https://docs.unity3d.com/ja/2018.4/ScriptReference/UI.ScrollRect.OnBeginDrag.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/f0f0a2e9-7c63-be9f-75c3-34c848687671.png)


### OnDrag

https://docs.unity3d.com/ja/2018.4/ScriptReference/EventSystems.EventTrigger.OnDrag.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/67d23ae2-0ccb-7379-3f55-2bf9fda96870.png)



### Image.sprite

https://docs.unity3d.com/ja/2018.4/ScriptReference/UI.Image-sprite.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/7a4bfef3-2291-8b9b-53ae-a8508848bde1.png)


### Input.mousePosition

https://docs.unity3d.com/ja/2020.3/ScriptReference/Input-mousePosition.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/9524f058-6466-c17b-9555-1e2268ac52da.png)


### GameObject.transform.position

https://docs.unity3d.com/ja/2020.3/ScriptReference/GameObject.html

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/74ef3b2d-9972-07d6-89a5-981f2c51c7c1.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/2710623/5ddc2444-4c16-b691-0f3b-5ab118ad8739.png)



## その他

Section1


github コミット分（個人確認用　privateなので見れません）

https://github.com/RYA234/LearnFarmRPG/commit/6003a491fc93e50c9d88db93daa759300784f2d5