经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 软件/图像 » unity » 查看文章
unity实现鼠标拖住3D物体
来源:jb51  时间:2019/7/17 10:35:28  对本文有异议

本文实例为大家分享了unity实现鼠标拖住3D物体的具体代码,供大家参考,具体内容如下

把该脚本直接挂在要拖拽的物体上即可

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class ModelDrages : MonoBehaviour
  6. {
  7.  
  8. //发射射线的摄像机
  9. private Camera cam;
  10. //射线碰撞的物体
  11. private GameObject go;
  12. //射线碰撞物体的名字
  13. public static string btnName;
  14. private Vector3 screenSpace;
  15. private Vector3 offset;
  16. private bool isDrage = false;
  17.  
  18. // Use this for initialization
  19. void Start ()
  20. {
  21. cam = Camera.main;
  22. }
  23.  
  24. // Update is called once per frame
  25. void Update ()
  26. {
  27. //整体初始位置
  28. Ray ray = cam.ScreenPointToRay(Input.mousePosition);
  29. //从摄像机发出到点击坐标的射线
  30. RaycastHit hitInfo;
  31. if (isDrage == false)
  32. {
  33. if(Physics .Raycast (ray,out hitInfo))
  34. {
  35. //划出射线 只有在Scene视图中才能看到
  36. Debug.DrawLine(ray.origin, hitInfo.point);
  37. go = hitInfo.collider.gameObject;
  38. print(btnName);
  39. screenSpace = cam.WorldToScreenPoint(go.transform.position);
  40. offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
  41. //物体的名字
  42. btnName = go.name;
  43. //组件的名字
  44. }
  45. else
  46. {
  47. btnName = null;
  48. }
  49. }
  50. if(Input.GetMouseButton(0))
  51. {
  52. Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
  53. Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
  54. if (btnName != null)
  55. {
  56. go.transform.position = currentPosition;
  57. }
  58. isDrage = true;
  59. }
  60. else
  61. {
  62. isDrage = false;
  63. }
  64. }
  65.  
  66. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号