查看: 487|回复: 0
打印 上一主题 下一主题

[其他] 鼠标拖动物体移动(纯代码+注释)

[复制链接]

9903

主题

126

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
53456
精华
316

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2015-9-27 01:34:15 |只看该作者 |倒序浏览
鼠标拖动物体移动(纯代码+注释)

  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.     }
复制代码
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

关闭

站长推荐上一条 /1 下一条

手机版|纳金网 ( 闽ICP备08008928号

GMT+8, 2024-5-6 11:49 , Processed in 0.174787 second(s), 29 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部