[Unity] 如何在Unity3d中拖拽任意的对象

查看:883 |回复:14 | 2015-11-16 16:18:21

您需要 登录 才可以下载或查看,没有账号?注册

x
目的 : 在没有使用刚体组件的情况下, 我们能简单的通过 鼠标位置 得到目标对象,其实我们利用的原理很简单,就是用射线来与物体做相交检测!下面开始
第一步: 在3D项目中设置场景. 一个空对象命名为: DragAndDrop ,和创建一些其他的游戏对象 如 sphere, cube 等
– 感觉如下l;
Center.jpg 第二步: C# 脚本命名为 “GameobjectDragAndDrop”.
第三步: 添加方法:
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject target = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
target = hit.collider.gameObject;
}
return target;
}
第四步: 在Update 方法中
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo;
target = ReturnClickedObject(out hitInfo);
if (target != null)
{
isMouseDrag = true;
Debug.Log("target position :" + target.transform.position);
//Convert world position to screen position.
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(0))
{
isMouseDrag = false;
}
if (isMouseDrag)
{
//track mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//convert screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//It will update target gameobject's current postion.
target.transform.position = currentPosition;
}
}
第五步: 运行程序,然后拖拽对象就OK了啊,好了本篇unity3d教程到此结束,下篇我们再会!


2015-11-16 16:18:21  
 赞 赞 1

使用道具 登录

14个回答,把该问题分享到群,邀请大神一起回答。
2#
噢? 这个 有点意思
回复 收起回复
2015-11-16 17:47:05   回复
 赞 赞 1

使用道具 登录

3#
好资源~!点赞
回复 收起回复
2015-11-16 20:02:29   回复
 赞 赞 1

使用道具 登录

4#
好资源~
回复 收起回复
2015-11-17 09:33:23   回复
 赞 赞 1

使用道具 登录

5#
好像就是射线找到目标,然后检测鼠标位置,改变物体坐标到鼠标位置,是这样吧
回复 收起回复
2015-11-19 15:42:29   回复
 赞 赞 1

使用道具 登录

6#
赞一个~
回复 收起回复
2015-11-19 18:19:09   回复
 赞 赞 1

使用道具 登录

7#
感谢分享.
回复 收起回复
2018-7-7 13:12:31   回复
 赞 赞 1

使用道具 登录

8#
挺好的方法 很实用!!! 效果不错!!!
回复 收起回复
2018-7-7 20:34:46   回复
 赞 赞 1

使用道具 登录

9#
感谢分享
回复 收起回复
2018-10-19 08:53:42   回复
 赞 赞 1

使用道具 登录

10#
拖拽功能的话一般在UI上更常用吧
回复 收起回复
2018-10-19 23:01:30   回复
 赞 赞 1

使用道具 登录

11#
谢谢楼主分享
回复 收起回复
2018-10-20 08:34:44   回复
 赞 赞 1

使用道具 登录

12#
111
回复 收起回复
2018-10-20 08:43:04   回复
 赞 赞 1

使用道具 登录

13#
6666666666
回复 收起回复
2018-10-20 10:32:45   回复
 赞 赞 1

使用道具 登录

14#

                                                           资源发布哪家强?元素首发称大王!
回复 收起回复
2018-10-20 10:37:08   回复
 赞 赞 1

使用道具 登录

15#
好看
回复 收起回复
2018-12-18 08:22:31   回复
 赞 赞 1

使用道具 登录

CG 游戏行业专业问题

Unity3D技术手机游戏引擎手游引擎
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表