代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragNGUI : MonoBehaviour {
private bool m_isDrag = false;
private bool m_temp_bool = false;
private GameObject m_Anchor = null;
private UIAtlas m_Atlas = null;
private string m_NameSprite = null;
private int m_Width = 60;
private int m_Height = 60;
// Use this for initialization
void Start()
{
if (this.GetComponent<UISprite>())
{
m_Atlas = this.GetComponent<UISprite>().atlas;
m_NameSprite = this.GetComponent<UISprite>().spriteName;
}
}
// Update is called once per frame
void Update()
{
if (!m_temp_bool && StaticFunction.IsHoverNGUI(Input.mousePosition) == this.gameObject)
{
//Debug.Log(StaticFunction.IsHoverNGUI(Input.mousePosition).name);
if (Input.GetMouseButtonDown(0))
{
m_isDrag = true;
m_temp_bool = true;
CreateAnchorObj();
}
}
if (m_temp_bool && m_isDrag)
{
Drag();
}
if (m_temp_bool && Input.GetMouseButtonUp(0))
{
m_isDrag = false;
m_temp_bool = false;
Destroy(m_Anchor);
Config.IsCreateMan = true;
}
}
private void CreateAnchorObj()
{
m_Anchor = new GameObject("Anchor");
m_Anchor.transform.parent = GameObject.Find("UI Root").transform;
m_Anchor.transform.localPosition = Vector3.zero;
if (m_Atlas != null)
{
m_Anchor.AddComponent<UISprite>();
UISprite temp = m_Anchor.GetComponent<UISprite>();
temp.atlas = m_Atlas;
temp.spriteName = m_NameSprite;
//m_Anchor.GetComponent<UIWidget>().width = this.GetComponent<UIWidget>().width;
//m_Anchor.GetComponent<UIWidget>().height = this.GetComponent<UIWidget>().height;
m_Anchor.GetComponent<UIWidget>().width = m_Width;
m_Anchor.GetComponent<UIWidget>().height = m_Height;
}
m_Anchor.transform.localScale = new Vector3(1, 1, 1);
}
private void Drag()
{
if (!m_Anchor) return;
Vector3 temp = Input.mousePosition;
temp.x -= Screen.width / 2.0f;
temp.y -= Screen.height / 2.0f;
m_Anchor.transform.localPosition = temp;
//this.transform.position = m_Anchor.transform.position;
}
}