找回密码
 立即注册
查看: 11224|回复: 86

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

[复制链接]
发表于 2015-11-16 16:23 | 显示全部楼层 |阅读模式
目的 : 在没有使用刚体组件的情况下, 我们能简单的通过 鼠标位置 得到目标对象,其实我们利用的原理很简单,就是用射线来与物体做相交检测!下面开始
第一步: 在3D项目中设置场景. 一个空对象命名为: DragAndDrop ,和创建一些其他的游戏对象 如 sphere, cube 等
– 感觉如下l;
第二步: 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教程到此结束,下篇我们再会!

添加如下声明:补充

    GameObject target;
    private bool isMouseDrag;
    private Vector3 screenPosition;
    private Vector3 offset;  

本帖子中包含更多资源

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

×
发表于 2016-7-15 20:56 | 显示全部楼层

感谢楼主的无私分享!
发表于 2016-7-17 22:37 | 显示全部楼层
这我看看情况啊
发表于 2016-7-22 16:37 | 显示全部楼层

感谢楼主的无私分享!
发表于 2016-8-1 19:42 | 显示全部楼层

不错 不错 不错
发表于 2016-8-4 22:25 | 显示全部楼层
挺好的.来多几个demo叫好了
发表于 2016-10-7 20:47 | 显示全部楼层

感谢楼主的无私分享!
发表于 2016-10-27 10:14 | 显示全部楼层

不错 不错 不错
发表于 2016-11-2 09:41 | 显示全部楼层

不错 不错 不错
发表于 2016-12-30 10:24 | 显示全部楼层

不错 不错 不错
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-22 20:00 , Processed in 0.102703 second(s), 28 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

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