using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class MYTEST : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public bool IsDrag;
public Transform OtherBox;
public Transform SelfBox;
public Vector2 OriginPos;
public GameObject ResCube;
public int TerrainLayMask;
private GameObject _createGo;
void Awake()
{
OriginPos = transform.GetComponent<RectTransform>().anchoredPosition;
TerrainLayMask = LayerMask.GetMask("Terrain");
}
private void Update()
{
if (!IsDrag) return;
InOrOutUI(Input.mousePosition.x > 100);
if (_createGo == null) return;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//摄像机到屏幕的射线
RaycastHit hit;
Vector3 newPos;
if (Physics.Raycast(ray, out hit,1000, 1 << LayerMask.NameToLayer("Terrain")))//如果碰到Collider,就把物体的位置变成这个位置
{
newPos = hit.point;
Debug.Log("碰到Collider>>>"+ newPos);
}
else//如果没有碰到,就把屏幕坐标转换为世界坐标
{
var pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane + 300f));
newPos = pos;
Debug.LogError("NO碰到>>>>>"+ newPos);
}
// _createGo.transform.position = newPos;
_createGo.transform.position = new Vector3(newPos.x, newPos.y+25, newPos.z);
}
void InOrOutUI(bool b)
{
if (b)
{
if (transform.parent == OtherBox) return;
transform.SetParent(OtherBox);
if (_createGo == null)
{
_createGo = Instantiate<GameObject>(ResCube);
}
else
{
_createGo.SetActive(true);
}
}
else
{
if (transform.parent == SelfBox) return;
transform.SetParent(SelfBox);
transform.localScale = Vector3.one;
if (_createGo != null)
{
_createGo.SetActive(false);
}
}
}
// begin dragging
public void OnBeginDrag(PointerEventData eventData)
{
IsDrag = true;
Debug.Log("OnBeginDrag");
SetDraggedPosition(eventData);
}
// during dragging
public void OnDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
// end dragging
public void OnEndDrag(PointerEventData eventData)
{
IsDrag = false;
Debug.Log("OnEndDrag");
SetDraggedPosition(eventData);
transform.GetComponent<RectTransform>().anchoredPosition = OriginPos;
}
/// <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;
}
}
}