// DragTest-2D 参照
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//CameraのProjectionはOrthographicに。
[RequireComponent(typeof(Image))]
public class DragObj : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
private Vector2 prevPos;
private Image image;
void Start()
{
image = this.GetComponent();
}
public void OnBeginDrag(PointerEventData eventData)
{
// ドラッグ前の位置を記憶しておく
prevPos = transform.position;
}
public void OnDrag(PointerEventData eventData)
{
Vector3 TargetPos = Camera.main.ScreenToWorldPoint(eventData.position);
TargetPos.z = 0;
transform.position = TargetPos;
}
public void OnEndDrag(PointerEventData eventData)
{
bool flg = true;
var raycastResults = new List();
EventSystem.current.RaycastAll(eventData, raycastResults);
foreach (var hit in raycastResults)
{
if (hit.gameObject.CompareTag("image"))
{
transform.position = hit.gameObject.transform.position;
image.enabled = false;
// Destroy(image);
}
}
if (flg)
{
transform.position = prevPos;
}
}
}