[Unity]背包效果-使用NGUI實現物品的拖拽效果Drag


背包效果-使用NGUI實現物品的拖拽效果Drag

效果實現如圖

對象層級關系圖


  • PacketCell - Right

    • 對象作為單元格背景
  • PacketContainer

    • 對象作為單元格容器
  • PacketLabel

    • 對象作為單元格物體
  • PacketCell - Left

    • 對象作為單元格背景
  • PacketContainer

    • 對象作為單元格容器
  • PacketLabel

    • 對象作為單元格物體
  • 'Label - Middle'

    • 用來顯示當前文字處於哪個位置

物體能夠被拖拽的幾個條件

  • 碰撞器 BoxCollider
  • 拖拽功能 UIDragDropItem

創建第一個拖拽功能的空子類

using System;
using UnityEngine;

/// <summary>
/// 第一個自己創建的拖拽功能
/// </summary>
public class MyFirstDragDropItem:UIDragDropItem
{
	
}

容器可以監測正在被拖拽物體是否到自己對象位置的幾個條件

  • 碰撞器 BoxCollider
  • 容器功能 UIDragDropContainer

GMUser.cs

using System;

/// <summary>
/// 用戶管理器
/// </summary>
public class GMUserManager
{
	//存儲當前正在玩游戲的玩家信息
	private static GMUser user = null;
	//公開訪問器
	public static GMUser User{ 
		get {
			if (GMUserManager.user == null) {
				GMUserManager.user = new GMUser ();
			}

			return GMUserManager.user;
		}
	}
}

public class GMUser
{
	//游戲用戶的姓名
	public string Name{set;get;}
	public GMUser ()
	{
		//設置每個用戶的默認姓名是Right
		this.Name = "Right";
	}
}

MyFirstDragDropItem.cs

using System;
using UnityEngine;

/// <summary>
/// 第一個自己創建的拖拽功能
/// </summary>
public class MyFirstDragDropItem:UIDragDropItem
{

	private GameObject sourceParent;
	/// <summary>
	/// 重寫父類的拖拽開始函數
	/// </summary>
	protected override void OnDragDropStart ()
	{
		//當拖拽開始時存儲原始的父對象
		this.sourceParent = this.transform.parent.gameObject;
		base.OnDragDropStart ();
	}
	/// <summary>
	/// 重寫父類的拖拽釋放函數
	/// </summary>
	protected override void OnDragDropRelease (GameObject surface)
	{
		//如果不是拖拽到場景表面的話
		if (!surface.name.Equals ("UI Root")) {
			//尋找surface對象的父對象
			GameObject cell = surface.transform.parent.gameObject;

			//判斷當前單元格的對象姓名
			if (cell.name.Equals ("PacketCell - Left")) {
				GMUserManager.User.Name = "Left";
			} 
			if (cell.name.Equals ("PacketCell - Right")) {
				GMUserManager.User.Name = "Right";
			}
		} else {
			//其他的錯誤位置時,重置父子關系
			this.transform.parent = this.sourceParent.transform;
		}

		//最終調用父類的功能
		base.OnDragDropRelease(surface);
		//調整位置
		this.transform.localPosition = new Vector3(0,0,0);
	}
}

Test.script

掛載在MainCamera對象上的腳本

using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour {

	//指向游戲中間的那個label控件
	public UILabel	label;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () 
	{
		this.label.text = GMUserManager.User.Name;
	}
}

工程存放位置


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM