代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragCreate : MonoBehaviour
{
public GameObject Cube;
public GameObject Place;
/// <summary>
/// 按下响应
/// </summary>
public void PointerDown()
{
OnBeginDrag();
}
/// <summary>
/// 开始拖拽
/// </summary>
public void OnBeginDrag()
{
GameObject game = Instantiate(Cube);
game.SetActive(true);
generateGame = game;
float distance = Camera.main.transform.InverseTransformPoint(Place.transform.position).z;
generateGame.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
Input.mousePosition.y, distance));
generateGame.transform.rotation = Place.transform.rotation;
Place.SetActive(true);
}
private GameObject generateGame;
/// <summary>
/// 进行拖拽
/// </summary>
public void OnDrag()
{
float distance = Camera.main.transform.InverseTransformPoint(Place.transform.position).z;
generateGame.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
Input.mousePosition.y, distance));
}
/// <summary>
/// 结束拖拽
/// </summary>
public void OnEndDrag()
{
if (generateGame.transform.position.x > Place.transform.position.x - 0.3f
&& generateGame.transform.position.x < Place.transform.position.x + 0.3f
&& generateGame.transform.position.y > Place.transform.position.y - 0.3f
&& generateGame.transform.position.y < Place.transform.position.y + 0.3f)
{
Place.SetActive(false);
generateGame.transform.position = Place.transform.position;
}
else
{
Place.SetActive(false);
Destroy(generateGame);
}
}
}
脚本挂载和层级:
?
|