首页 > 代码库 > unity中 拖拽随意的对象

unity中 拖拽随意的对象

孙广东   2015.8.16 

目的 :  我们能简单的通过 鼠标位置 得到目标对象  假设没有使用刚体组件  


Step - 1: 在3D项目中设置场景.  一个空对象命名为: DragAndDrop   ,和创建一些其它的游戏对象 如 sphere, cube 等 

- 感觉例如以下l;

技术分享


Step - 2: C# 脚本命名为  "GameobjectDragAndDrop". 

Step - 3: 加入方法:

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;
    }

Step - 4: 在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;
        }
 
    }

Step - 6: 执行程序,然后拖拽对象就OK了啊。。


unity中 拖拽随意的对象