1. 程式人生 > >unity實現物品或技能圖示的拖拽功能

unity實現物品或技能圖示的拖拽功能

在設計揹包或者技能欄的時候,通常採用MVC模式。

Model指令碼讀取存放在資料庫中的物品或技能的相關資源(Icon,prefabs)

view指令碼將讀取的資源顯示在揹包或技能欄中。

而Controller指令碼我則用來實現物品或技能的拖拽。而我的Drag指令碼分在Controller中,給每個物品或技能資源都掛上指令碼,實現拖拽核心功能。

而Drag指令碼中的方法Unity已提供介面。

主要方法是public void OnBeginDrag (PointerEventData eventData)

                    public void OnDrag(PointerEventData eventData)

                    public void OnEndDrag(PointerEventData eventData)

而函式private void SetDraggedPosition(PointerEventData eventData)是Unity提供的讓拖拽目標跟隨滑鼠移動的方法,我在上面3個函式中都進行了呼叫。

Start()和OnbeginDrag中的資料都是為OnEndDrag中判斷能否交換目標物品的位置做準備,以及如果能則實現交換。實現的方法千差萬別,感覺我這裡寫的方法適用範圍很小,若要參考推薦重寫這部分功能(判斷能否交換及實現交換)

程式碼如下

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
/// <summary>
/// MVC-controll;
/// </summary>
public class Drag : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler {
	public Transform bg;
	public Transform rawParent;
	public GameObject exchange;
	// begin dragging
	public void Start(){
		bg = GameObject.Find ("Canvas_Windows").transform;
	}

	public void OnBeginDrag (PointerEventData eventData)
	{   if (gameObject.GetComponent<Image> ().sprite == null) {
			return;
		}
		rawParent = transform.parent;
		transform.SetParent (bg);
		SetDraggedPosition (eventData);
		gameObject.GetComponent<Image> ().raycastTarget = false;

	}

	// during dragging
	public void OnDrag(PointerEventData eventData)
	{    if (gameObject.GetComponent<Image> ().sprite == null) {
			return;
		}
		SetDraggedPosition(eventData);
	}

	// end dragging
	public void OnEndDrag(PointerEventData eventData)
	{    if (gameObject.GetComponent<Image> ().sprite == null) {
			return;
		}
		//SetDraggedPosition(eventData);
		GameObject goal=eventData.pointerCurrentRaycast.gameObject;
		Debug.Log (goal.name);
		if (goal.transform.parent.name == "Icon") {
			
		 
			exchange = Instantiate (goal);
			transform.SetParent (goal.transform.parent);
			transform.localPosition = Vector3.zero;
			Destroy (exchange,0.2f);
			Destroy (goal,0.3f);
            GameObject k =	Instantiate (exchange, rawParent);
			k.transform.localPosition = Vector3.zero;
			k.GetComponent<Image> ().enabled = true;

			gameObject.GetComponent<Image> ().raycastTarget = true;
		} 

		else {
			transform.SetParent (rawParent);
			transform.localPosition = Vector3.zero;
			gameObject.GetComponent<Image> ().raycastTarget = true;
		}
	}

	/// <summary>
	/// set position of the dragged game object
	/// </summary>
	/// <param name="eventData"></param>
	private void SetDraggedPosition(PointerEventData eventData)
	{
		var rt = gameObject.GetComponent<RectTransform>();

		// transform the screen point to world point int rectangle
		Vector3 globalMousePos;
		if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
		{
			rt.position = globalMousePos;
		}
	}
}