目的 : 在没有使用刚体组件的情况下, 我们能简单的通过 鼠标位置 得到目标对象,其实我们利用的原理很简单,就是用射线来与物体做相交检测!下面开始
第一步: 在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;
|