纳金网

标题: 鼠标拖动物体移动(纯代码+注释) [打印本页]

作者: 烟雨    时间: 2015-9-27 01:34
标题: 鼠标拖动物体移动(纯代码+注释)
鼠标拖动物体移动(纯代码+注释)

  1. // Use this for initialization
  2.     bool isOk = false;
  3.    
  4.     void Start () {
  5.         this.GetComponent<MeshRenderer>().material.color = Color.red;
  6.     }
  7.    
  8.     // Update is called once per frame
  9.     void Update()
  10.     {
  11.         //判断是否按下左键
  12.         if (Input.GetMouseButtonDown(0))
  13.         {
  14.             //发射线
  15.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  16.             RaycastHit hit;
  17.             if (Physics.Raycast(ray, out hit))
  18.             {
  19.                 //我要移动的物体名字叫Sphere
  20.                 if (hit.transform.name == "Sphere")
  21.                 {
  22.                     isOk = true;
  23.                 }
  24.             }
  25.         }
  26.         //抬起左键 isok为假
  27.         if(Input.GetMouseButtonUp(0)){
  28.             isOk = false;

  29.         }

  30.         //isok为真,移动物体
  31.         if (isOk)
  32.         {
  33.             //获取需要移动物体的屏幕坐标
  34.             Vector3 targer = Camera.main.WorldToScreenPoint(this.transform.position);

  35.             //获取鼠标的屏幕坐标,,将物体的屏幕坐标的z轴赋给鼠标坐标
  36.             Vector3 mouse = Input.mousePosition;
  37.             mouse.z = targer.z;

  38.             //将鼠标的屏幕坐标转变成世界坐标
  39.             Vector3 mouseScreenPos = Camera.main.ScreenToWorldPoint(mouse);
  40.             //移动的物体的位置就等于转换成世界坐标的鼠标位置
  41.             this.transform.position = mouseScreenPos;
  42.         }
  43.                
  44.         
  45.     }
复制代码





欢迎光临 纳金网 (http://www.narkii.com/club/) Powered by Discuz! X2.5