17

最近では、Unity で UI 要素をドラッグするのは非常に簡単です。いくつかの UI アイテムを作成します。Component -> Event -> Event Triggerを追加します。以下のスクリプトにドロップします。4 つの明らかなトリガーをクリックして追加します。あなたは終わった。

でも。

ポインター座標UI 座標(RectTransform などで見られるように)の関係に完全に迷っています。

以下: UI パネルを指の下で正しく移動するにはDragItどうすればよいでしょうか?

1 つの大きなパネルがあり、10 個の UIButtonDragsterがボタン上にあるとします。RectTransform 座標とマウス ポインターの関係は何ですか...

つまり、下の DragIt() でボタンの 1 つを移動するにはどうすればよいでしょうか。

/* modern Unity drag of UI element */
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class Dragster:MonoBehaviour
    {
    public int index; // number each of your UI items
    static bool beingDragged = false;
    static int dragFrom;
    public void DragStart()
        {
        beingDragged = true; dragFrom = index;
        }
    public void DragIt()
        {
        ? ? W T F ? ?
        }
    public void DragEnd()
        {
        beingDragged = false;
        }
    public void DroppedBra()
        {
        Debig.Log("Drag: from/to " +dragFrom +" --> " +index);
        }
    }
4

4 に答える 4

12

あなたのスクリプトにドラッグインターフェースを実装させます

public class Dragster:MonoBehaviour,IBeginDragHandler, IEndDragHandler, IDragHandler

あなたのDragIt機能を次のようにします

public void OnDrag(PointerEventData eventData)
{
    transform.position += (Vector3)eventData.delta;
}

そのイベントのデルタ (マウスがどれだけ移動したか) にアクセスして、オブジェクトを移動できるようにします。

それでも EventTrigger コンポーネントを使用したい場合 (あまり好まない方法)、DragIt関数をに変更DragIt(PointerEventData eventData)し、トリガーのドロップダウンで Dynamic EvenData オプションを使用して、デルタ情報にアクセスする PointerEventData を受け取る必要があります。


これは、Uri & Colton のコードに基づいた、「UnityEngine.UI」アイテムのドラッグ アンド ドロップの完全なソリューションです。コピーして貼り付けるだけです。

Unity UI、wtt Colton & Uri のための驚異的なコピー アンド ペーストの簡単な完璧なドラッグ アンド ドロップ:

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

public class UNCDraggable:MonoBehaviour,
IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler
    {
    public Image ghost;
    // note DON'T try to drag the actual item: it's not worth the hassle.
    // a problem arises where you can't have it on top (as you would want
    // visually), and still easily get the drops. always use a ghost.
    // even if you want the "original invisible" while dragging,
    // simply hide it and use a ghost. everything is tremendously
    // easier if you do not move the originals.
    
    void Awake()
        {
        ghost.raycastTarget = false;
        // (just in case you forgot to do that in the Editor)
        ghost.enabled = false;
        }
    
    public void OnBeginDrag(PointerEventData eventData)
        {
        ghost.transform.position = transform.position;
        ghost.enabled = true;
        }

    public void OnDrag(PointerEventData eventData)
        {
        ghost.transform.position += (Vector3)eventData.delta;
        }

    public void OnEndDrag(PointerEventData eventData)
        {
        ghost.enabled = false;
        }
    
    public void OnDrop(PointerEventData data)
        {
        GameObject fromItem = data.pointerDrag;
        if (data.pointerDrag == null) return; // (will never happen)
        
        UNCDraggable d = fromItem.GetComponent<UNCDraggable>();
        if (d == null)
          {
          // means something unrelated to our system was dragged from.
          // for example, just an unrelated scrolling area, etc.
          // simply completely ignore these.
          return;
          // note, if very unusually you have more than one "system"
          // of UNCDraggable items on the same screen, be careful to
          // distinguish them! Example solution, check parents are same.
          }
        
        Debug.Log ("dropped  " + fromItem.name +" onto " +gameObject.name);
        
        // your code would look probably like this:
        YourThings fromThing = fromItem.GetComponent<YourButtons>().info;
        YourThings untoThing = gameObject.GetComponent<YourButtons>().info;
        
        yourBossyObject.dragHappenedFromTo(fromThing, untoThing);
        }
    }
于 2016-05-27T02:37:53.860 に答える
9

まず第一に、この投稿の他のすべての回答は非常にうまく機能しています。私はこれに長い間取り組んできたので、ここに投稿したいと思いました。他の不要な UI オブジェクトがドラッグされるのを防ぐ方法を追加します。

私の公式の目標は、 を使用せずにこれを行う方法を提供することでしたbool beingDragged = false;。そのようにすると、どちらがドラッグされているのButtonかわかりません。Image

UI のドラッグ:

を使用して RectTransform のスクリーンポイントをローカル ポイントに変換し、子 UI が正確にどこにあるかを調べるためにRectTransformUtility使用します。Canvas.transform.TransformPoint

public Canvas parentCanvasOfImageToMove;
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvasOfImageToMove.transform as RectTransform, eventData.position, parentCanvasOfImageToMove.worldCamera, out pos);
UIToMove.transform.position = parentCanvasOfImageToMove.transform.TransformPoint(pos);

ドラッグ コードは、他の回答の他のドラッグ コードよりも複雑に見えますが、すべてのキャンバス カメラ モードで動作しているようです。

ドラッグしようとしているオブジェクトの検出:

OnBeginDragこれを行う最も簡単な方法は、ユーザーが関数にドラッグしたいオブジェクトを保存するために使用できるグローバル変数を作成し、そのオブジェクトをOnDrag. OnEndDragが呼び出されたときにそのオブジェクトを null に設定します。

objectToBeDragged = eventData.pointerCurrentRaycast.gameObject;

これは、OnBeginDrag関数内で 1 回実行してから、グローバル変数に保存する必要があります。

OnDrag関数内で次のことを行うことはできません

if (eventData.pointerCurrentRaycast.gameObject == someOtherUI)
{
   someOtherUI....drag
}

うまくいくはずなのに、うまくいかないこともあります。中に null を返すことさえありますOnDrag。そのため、OnBeginDrag関数で実行する必要があります。

ボタンと画像の検出とドラッグ:

UI が単なる であるかどうかを検出し、ImageをドラッグするのImageは非常に簡単です。

objectToBeDragged  = eventData.pointerCurrentRaycast.gameObject;
Button tempButton = objectToBeDragged.GetComponent<Button>();
Image tempImage = objectToBeDragged.GetComponent<Image>();

そうtempImageなく nulltempButtonある場合null、それは画像です。

UI が単に a であるかどうかを検出し、aButtonをドラッグするのButtonは簡単ではありません。ボタンがサイド/エッジでクリックされると、の名前Buttonが返されますが、これは問題ありません。しかし、ほとんどの場合、ボタンのインスタンスまたは名前を返さずに(オブジェクト)を返す途中でa のクリックButtonが発生します。テキストをボタンとして移動することはできません。うまくいきません。ButtonText

objectToBeDragged  = eventData.pointerCurrentRaycast.gameObject;
Button tempButton = objectToBeDragged.GetComponent<Button>();
Image tempImage = objectToBeDragged.GetComponent<Image>();
Text tempText = objectToBeDragged.GetComponent<Text>();

null でない場合tempTextは、Text の Image および Button コンポーネントを取得します。が null ではなく、null でない場合、それはです。GetComponentInParentImageButtonButton

if (tempText != null)
{
    tempButton = tempText.GetComponentInParent<Button>();
    tempImage = tempText.GetComponentInParent<Image>();
    if (tempButton != null && tempImage != null)
    {
        //This is a Button
    }
}

以下は、UI イメージ/パネルとボタンをドラッグする完全なスクリプトです。ドラッグする必要がある任意のボタンを UIButtons配列に配置し、ドラッグする必要がある任意のパネル/画像を配列に配置する必要がありますUIPanels。配列にない他の UI は無視されます。

public class UIDRAGGER : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Canvas parentCanvasOfImageToMove;

    //10 UI Buttons (Assign in Editor)
    public Button[] UIButtons;

    //2 UI Panels/Images (Assign in Editor)
    public Image[] UIPanels;

    //Hold which Button or Image is selected
    private Button selectedButton;
    private Image selectedUIPanels;

    //Used to make sure that the UI is position exactly where mouse was clicked intead of the default center of the UI
    Vector3 moveOffset;

    //Used to decide which mode we are in. Button Drag or Image/Panel Mode
    private DragType dragType = DragType.NONE;


    void Start()
    {
        parentCanvasOfImageToMove = gameObject.GetComponent<Canvas>();
    }

    //Checks if the Button passed in is in the array
    bool buttonIsAvailableInArray(Button button)
    {
        bool _isAValidButton = false;
        for (int i = 0; i < UIButtons.Length; i++)
        {
            if (UIButtons[i] == button)
            {
                _isAValidButton = true;
                break;
            }
        }
        return _isAValidButton;
    }

    //Checks if the Panel/Image passed in is in the array
    bool imageIsAvailableInArray(Image image)
    {
        bool _isAValidImage = false;
        for (int i = 0; i < UIPanels.Length; i++)
        {
            if (UIPanels[i] == image)
            {
                _isAValidImage = true;
                break;
            }
        }
        return _isAValidImage;
    }

    void selectButton(Button button, Vector3 currentPos)
    {
        //check if it is in the image array that is allowed to be moved
        if (buttonIsAvailableInArray(button))
        {
            //Make the image the current selected image
            selectedButton = button;
            dragType = DragType.BUTTONS;
            moveOffset = selectedButton.transform.position - currentPos;
        }
        else
        {
            //Clear the selected Button
            selectedButton = null;
            dragType = DragType.NONE;
        }
    }

    void selectImage(Image image, Vector3 currentPos)
    {
        //check if it is in the image array that is allowed to be moved
        if (imageIsAvailableInArray(image))
        {
            //Make the image the current selected image
            selectedUIPanels = image;
            dragType = DragType.IMAGES;
            moveOffset = selectedUIPanels.transform.position - currentPos;
        }
        else
        {
            //Clear the selected Button
            selectedUIPanels = null;
            dragType = DragType.NONE;
        }
    }


    public void OnBeginDrag(PointerEventData eventData)
    {
        GameObject tempObj = eventData.pointerCurrentRaycast.gameObject;

        if (tempObj == null)
        {
            return;
        }

        Button tempButton = tempObj.GetComponent<Button>();
        Image tempImage = tempObj.GetComponent<Image>();
        Text tempText = tempObj.GetComponent<Text>();

        //For Offeset Position
        Vector2 pos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvasOfImageToMove.transform as RectTransform, eventData.position, parentCanvasOfImageToMove.worldCamera, out pos);


        //Button must contain Text then Image and Button as parant
        //Check if this is an image
        if (tempButton == null || tempImage == null)
        {
            //Button not detected. Check if Button's text was detected
            if (tempText != null)
            {
                //Text detected. Now Look for Button and Image in the text's parent Object
                tempButton = tempText.GetComponentInParent<Button>();
                tempImage = tempText.GetComponentInParent<Image>();

                //Since child is text, check if parents are Button and Image
                if (tempButton != null && tempImage != null)
                {
                    //This is a Button
                    selectButton(tempButton, parentCanvasOfImageToMove.transform.TransformPoint(pos));
                }
                //Check if there is just an image
                else if (tempImage != null)
                {
                    //This is an Image
                    selectImage(tempImage, parentCanvasOfImageToMove.transform.TransformPoint(pos));
                }
            }
            else
            {
                //This is an Image
                selectImage(tempImage, parentCanvasOfImageToMove.transform.TransformPoint(pos));
            }
        }
        //Check if there is just an image
        else if (tempImage != null)
        {
            selectImage(tempImage, parentCanvasOfImageToMove.transform.TransformPoint(pos));
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 pos;
        if (dragType == DragType.BUTTONS)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvasOfImageToMove.transform as RectTransform, eventData.position, parentCanvasOfImageToMove.worldCamera, out pos);
            selectedButton.transform.position = parentCanvasOfImageToMove.transform.TransformPoint(pos) + moveOffset;
        }
        else if (dragType == DragType.IMAGES)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvasOfImageToMove.transform as RectTransform, eventData.position, parentCanvasOfImageToMove.worldCamera, out pos);
            selectedUIPanels.transform.position = parentCanvasOfImageToMove.transform.TransformPoint(pos) + moveOffset;
        }
    }


    public void OnEndDrag(PointerEventData eventData)
    {
        //Buttons
        if (dragType == DragType.BUTTONS || dragType == DragType.IMAGES)
        {
            selectedButton = null;
            selectedUIPanels = null;
            dragType = DragType.NONE;
        }
    }

    DragType getCurrentDragType()
    {
        return dragType;
    }

    private enum DragType { NONE, BUTTONS, IMAGES };
}
于 2016-05-27T17:30:41.153 に答える
7

ドラッグのものについては、これを行うだけです:

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

public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
    
    
    
    public void OnBeginDrag(PointerEventData eventData) {
        
    }
    
    public void OnDrag(PointerEventData eventData) {
        //Debug.Log ("OnDrag");
        
        this.transform.position = eventData.position;

        }

    public void OnEndDrag(PointerEventData eventData) {
        Debug.Log ("OnEndDrag");
    
    }
}

これは、ドラッグするときに常に必要な 2 つの単純な機能を備えた同一の驚くべき URIPOPOV コードです。

// allow dragging with two basic problem fixes:
// - limit drag to the parent box
// - don't "jump" based on where you hold down

100% テスト済み:

using UnityEngine;
using UnityEngine.EventSystems;

public class AmazingUPDrag : MonoBehaviour,
               IBeginDragHandler, IDragHandler, IEndDragHandler
{
    Vector2 dragOffset = Vector2.zero;
    Vector2 limits = Vector2.zero;

    public void OnBeginDrag(PointerEventData eventData)
    {
        dragOffset = eventData.position - (Vector2)transform.position;
        limits = transform.parent.GetComponent<RectTransform>().rect.max;
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = eventData.position - dragOffset;
        var p = transform.localPosition;
        if (p.x < -limits.x) { p.x = -limits.x; }
        if (p.x > limits.x) { p.x = limits.x; }
        if (p.y < -limits.y) { p.y = -limits.y; }
        if (p.y > limits.y) { p.y = limits.y; }
        transform.localPosition = p;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        dragOffset = Vector2.zero;
    }
}
于 2016-05-27T12:15:18.583 に答える
0

わかりましたので、最初のソリューションは UI 要素 (オーバーレイ キャンバス) で機能します。ここでは、「現在のオブジェクト」をドラッグするために最低限必要だと思われるものを抽出します

using UnityEngine.EventSystems;

public class SomeObject : MonoBehaviour, IBeginDragHandler, IDragHandler
{
  private Canvas parentCanvas;
  private Vector3 moveOffset;

  void Start()
  {
      // get the "nearest Canvas"
      parentCanvas = GetComponentsInParent<Canvas>()[0];
      // you could get the Camera of this Canvas here as well and like @ina suggests add a null check for that and otherwise use Camera.Main
  }
  public void OnBeginDrag(PointerEventData eventData)
  {

      //For Offset Position so the object won't "jump" to the mouse/touch position
      RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, eventData.position, parentCanvas.worldCamera, out Vector2 pos);
      moveOffset = transform.position - parentCanvas.transform.TransformPoint(pos);

  }

  public void OnDrag(PointerEventData eventData)
  {
      RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, eventData.position, parentCanvas.worldCamera, out Vector2 pos);
      transform.position = parentCanvas.transform.TransformPoint(pos) + moveOffset;
  }
}

コードは私の実際のクラスから取得した行で構成されているため、テスト済みのスクリプトではありません。そしてもちろん、いくつかの使用法が必要です

于 2021-06-15T10:33:32.827 に答える