1. 程式人生 > >Unity中實現揹包物品拖動和更換位置

Unity中實現揹包物品拖動和更換位置

using UnityEngine;

using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class PointMoveController : MonoBehaviour,IBeginDragHandler, IDragHandler,IEndDragHandler
{

//// Use this for initialization
//void Start () 
//{

//}

//// Update is called once per frame
//void Update () 
//{ 
//}

private Vector3 Original;
private Transform OriginalParent;
/// <summary>
/// 開始拖動
/// </summary>
/// <param name="EventData"></param>
public void OnBeginDrag(PointerEventData EventData)
{
    OriginalParent = this.transform.parent;//設定父位置點
    Original = this.transform.position;
    this.GetComponent<CanvasGroup>().blocksRaycasts = false;//設定射線穿透
}
/// <summary>
/// 正在拖拽
/// </summary>
/// <param name="EventData"></param>
public void OnDrag(PointerEventData EventData)
{
    this.transform.position = Input.mousePosition;//當前位置為滑鼠所在位置
    if (EventData.pointerEnter.tag == "Weapon")
    {
        this.transform.SetParent(EventData.pointerEnter.transform);
    }
    if (EventData.pointerEnter.tag == "P")
    {
        this.transform.SetParent(EventData.pointerEnter.transform.parent);
    }
}
public void OnEndDrag(PointerEventData EventData)
{
    this.transform.localPosition = new Vector3(0,0,0);
    this.GetComponent<CanvasGroup>().blocksRaycasts = true;
    if (EventData.pointerEnter.tag == "P")
    {
        EventData.pointerEnter.transform.position = Original;
        EventData.pointerEnter.transform.SetParent(OriginalParent);
    }
    if (EventData.pointerEnter.tag == this.name)
    {
        this.transform.FindChild("Text").GetComponent<Text>().text = int.Parse(this.transform.FindChild("Text").GetComponent<Text>().text) +int.Parse(EventData.pointerEnter.transform.FindChild("Text").GetComponent<Text>().text)+"";
    }
    if (EventData.pointerEnter.tag == "BackGround")
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.tag = "P";
        this.transform.FindChild("Text").GetComponent<Text>().text = (int.Parse(this.transform.FindChild("Text").GetComponent<Text>().text) - 1) + "";
        OriginalParent = this.transform.parent;
        Original = this.transform.position;
    }
}

}