Unity3D点击UI图片生成模型预设物
目录
1、博客介绍
翻出来了之前一个两年前Demo,顺手传上来了,通过点击按钮或者其他UI元素生成模型预设物,并且随鼠标移动。
2、内容
(1)演示
(2)生成
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ClickButton : MonoBehaviour {
public GameObject Cube;
public GameObject Target;
private Button _btnCreate;
void Start () {
_btnCreate = GameObject.Find("Button").GetComponent<Button>();
_btnCreate.AddListener(EventTriggerType.PointerDown,OnDownButton);
}
public void OnDownButton(BaseEventData baseEventData)
{
GameObject cubePre = Instantiate(Cube);
if (Camera.main != null)
{
Vector3 targetSpace = Camera.main.WorldToScreenPoint(Target.transform.position);
cubePre.transform.position= Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetSpace.z));
}
}
}
生成脚本,,唯一注意的一点是,鼠标的屏幕坐标转世界坐标的时候,Z值选择场景内的某个物体作为参考值,必须将该物体的坐标转为屏幕坐标,再把转过的Z值组合鼠标点击位置转成世界坐标。
(3)生成物体移动
using UnityEngine;
using System.Collections;
public class CubeDragScript : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(OnMouseDown());
}
IEnumerator OnMouseDown()
{
if (Camera.main != null)
{
//三维物体世界坐标转屏幕坐标
Vector3 screenSpace = Camera.main.WorldToScreenPoint(transform.position);
//完成两个步骤 1.由于鼠标的坐标系是2维,需要转换成3维的世界坐标系
// 2.只有3维坐标情况下才能来计算鼠标位置与物理的距离,offset即是差值
//将鼠标屏幕坐标转为世界三维坐标,转换前的屏幕Z值套用Cube转换过得Z值,再算出Cube世界坐标与鼠标世界坐标的差值
Vector3 offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
while (Input.GetMouseButton(0))
{
Camera.main.GetComponent<MouseOrbit>().enabled = false;
//得到现在鼠标的屏幕坐标
Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
//物体的位置就是鼠标的世界坐标 + 差值
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
transform.position = curPosition;
//这个很重要,循环执行
yield return null;
}
}
if (Camera.main != null) Camera.main.GetComponent<MouseOrbit>().enabled = true;
}
}
注释一条条打的很清楚,直接看代码吧,MouseOrbit脚本是控制镜头旋转,拖动物体的时候禁用,需要源码和演示场景的跳转博主Github.
扫描二维码关注公众号,回复: 12862605 查看本文章
3、推送
工程Github:https://github.com/KingSun5/Demo_UICreateObj
4、结语
若是觉得博主的文章写的不错,不妨关注一下博主,点赞一下博文,另博主能力有限,若文中有出现什么错误的地方,欢迎各位评论指摘。
QQ交流群:806091680(Chinar)
该群为CSDN博主Chinar所创,推荐一下!我也在群里!
本文属于原创文章,转载请著名作者出处并置顶!!!!