从物品栏拖出物体,安装到指定位置
- 一、创建垂直滑动列表-物品栏
- 二、从物品栏拖出物体
- 三、左键移动物体+近距离安装
一、创建垂直滑动列表-物品栏
二、从物品栏拖出物体
- 创建Resources文件夹,在Resources文件夹下创建Prefabs文件夹
- 将要生成的实例物体放入Prefabs文件夹里
- 增加一个Button和Image
- 在Button下添加代码,str写实例名字,image选择合适的Image
- 代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DragSpawn : MonoBehaviour, IPointerDownHandler
{
public string str;//Resources文件夹下物体的名字
public Image image;//拖动之后的形状,删掉image即是无形状
private GameObject objDragSpawning;//正在拖拽的物体
private bool isDragSpawning = false;//是否正在拖拽
private void Start()
{
image.enabled = false;//开始image不显示
}
void Update()
{
if (isDragSpawning)
{
//刷新位置
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//发出从摄像机到点击坐标的射线
objDragSpawning.transform.position = ray.GetPoint(10);//ray.GetPoint(distance)沿着射线在distance距离单位的点
//拖动时的image
image.enabled = true;
image.transform.position = Input.mousePosition;
//拖动物体在鼠标为松开时不显示
objDragSpawning.SetActive(false);
//结束拖拽
if (Input.GetMouseButtonUp(0))
{
objDragSpawning.SetActive(true);
isDragSpawning = false;
objDragSpawning = null;
image.enabled = false;
}
}
}
//按下鼠标时开始生成实体
public void OnPointerDown(PointerEventData eventData)
{
str = "Prefabs/" + str;
GameObject prefab = Resources.Load(str);
if (prefab != null)
{
objDragSpawning = Instantiate(prefab);
isDragSpawning = true;
}
}
}
三、左键移动物体+近距离安装
- 在场景中放置目标物体,材质改为高亮颜色
- 当从物品栏拖出物体安装到目标物体处时,拖出物体消失,目标物体材质改为原本材质,销毁拖出物体
- 代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ControlMove : MonoBehaviour
{
public string str;//目标物体在Hierarchy面板的名字
public Material originMeterial;//声明物体本来的材质
private Transform target;
private Vector3 cubeScreenPos;
private Vector3 offset;
//定义一个全局的对象用来接收协程的返回值
IEnumerator ie;
void Start()
{
target= GameObject.Find(str).transform;
ie = OnMouseDown();
StartCoroutine(ie);//调用StartCoroutine(要调用的协程方法)开启协程
}
//协程
IEnumerator OnMouseDown()
{
//1. 得到物体的屏幕坐标
cubeScreenPos = Camera.main.WorldToScreenPoint(transform.position);
//2. 计算偏移量
//鼠标的三维坐标
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
//鼠标三维坐标转为世界坐标
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
offset = transform.position - mousePos;
//3. 物体随着鼠标移动
while (Input.GetMouseButton(0))
{
//目前的鼠标二维坐标转为三维坐标
Vector3 curMousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, cubeScreenPos.z);
//目前的鼠标三维坐标转为世界坐标
curMousePos = Camera.main.ScreenToWorldPoint(curMousePos);
//当与目标距离<2时,物体像目标移动
if (Vector3.Distance(transform.position, target.position) < 2)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, 5 * Time.deltaTime);
StopCoroutine(ie);//停止协程
if(transform.position==target.position)
{
target.GetComponent().material =originMeterial;//target材质改变
Destroy(gameObject);//删除挂载着脚本的游戏物体,销毁当前物体
}
}
else
{
//物体世界位置
transform.position = curMousePos + offset;
}
yield return new WaitForFixedUpdate(); //这个很重要,循环执行
}
}
}