Home > other >  Unity GameObject drag source
Unity GameObject drag source

Time:09-18

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

[RequireComponent (typeof (Image)))
Public class LightingOnList: MonoBehaviour, IBeginDragHandler IDragHandler, IEndDragHandler
{
Public bool dragOnSurfaces=true;

Private GameObject m_DraggingIcon;
Private RectTransform m_DraggingPlane;
Public GameObject prefab.

Public void OnBeginDrag (PointerEventData eventData)
{
The Debug. LogError (" OnBeginDrag ");
Var canvas=FindInParents (gameObject);
If (canvas==null)
return;

//We have clicked something that can be dragged.
//What we want to do is create an icon for this.
M_DraggingIcon=new GameObject (" icon ");

M_DraggingIcon. Transform. SetParent (canvas. The transform, false);
M_DraggingIcon. Transform. SetAsLastSibling ();

Var image=m_DraggingIcon. AddComponent (a);
//The icon will be under The cursor.
//We want it to be ignored by the event system.
CanvasGroup group=m_DraggingIcon. AddComponent (a);
Group. BlocksRaycasts=false;

Image. The Sprite=GetComponent (). The Sprite;
Image. SetNativeSize ();

If (dragOnSurfaces)
M_DraggingPlane=the transform as RectTransform;
The else
M_DraggingPlane=canvas. The transform as RectTransform;

SetDraggedPosition (eventData);
}

Public void OnDrag (PointerEventData data)
{
The Debug. LogError (" OnDrag ");
If (m_DraggingIcon!=null)
SetDraggedPosition (data);
}

Private void SetDraggedPosition (PointerEventData data)
{
The Debug. LogError (" SetDraggedPosition ");
If (dragOnSurfaces & amp; & Data pointerEnter!=null & amp; & Data. PointerEnter. Transform as RectTransform!=null)
M_DraggingPlane=data. PointerEnter. Transform as RectTransform;

Var rt=m_DraggingIcon. GetComponent (a);
Vector3 globalMousePos;
If (RectTransformUtility. ScreenPointToWorldPointInRectangle (m_DraggingPlane, data. The position, data pressEventCamera, out globalMousePos))
{
Rt. The position=globalMousePos;
Rt. Rotation=m_DraggingPlane. Rotation;
}
}

Public void OnEndDrag (PointerEventData eventData)
{
The Debug. LogError (" OnEndDrag - "+ eventData);

GameObject pointerEnter=eventData. PointerEnter;
GameObject lastPress=Instantiate (prefab, new Vector3 (0, 0, 0), Quaternion. Identity);

LastPress. The transform. The parent=pointerEnter. Transform;
LastPress. The transform. The position=eventData. Position;
If (m_DraggingIcon!=null)
Destroy (m_DraggingIcon);
}

The static public T FindInParents GameObject (go) where T: Component
{

If (go==null) return null;
Var comp=go. GetComponent (a);

If (comp!=null)
Return comp;

The Transform t=go. The Transform. The parent;
While (t!=null & amp; & Comp==null)
{
Comp=t.g ameObject. GetComponent (a);
T=t.p arent.
}

Return comp;
}
}

CodePudding user response:

Do you have any mobile the drag source
  • Related