- 最后登录
- 2021-7-6
- 注册时间
- 2012-12-27
- 阅读权限
- 90
- 积分
- 76145
- 纳金币
- 53456
- 精华
- 316
|
鼠标拖动物体移动(纯代码+注释)
- // Use this for initialization
- bool isOk = false;
-
- void Start () {
- this.GetComponent<MeshRenderer>().material.color = Color.red;
- }
-
- // Update is called once per frame
- void Update()
- {
- //判断是否按下左键
- if (Input.GetMouseButtonDown(0))
- {
- //发射线
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- RaycastHit hit;
- if (Physics.Raycast(ray, out hit))
- {
- //我要移动的物体名字叫Sphere
- if (hit.transform.name == "Sphere")
- {
- isOk = true;
- }
- }
- }
- //抬起左键 isok为假
- if(Input.GetMouseButtonUp(0)){
- isOk = false;
- }
- //isok为真,移动物体
- if (isOk)
- {
- //获取需要移动物体的屏幕坐标
- Vector3 targer = Camera.main.WorldToScreenPoint(this.transform.position);
- //获取鼠标的屏幕坐标,,将物体的屏幕坐标的z轴赋给鼠标坐标
- Vector3 mouse = Input.mousePosition;
- mouse.z = targer.z;
- //将鼠标的屏幕坐标转变成世界坐标
- Vector3 mouseScreenPos = Camera.main.ScreenToWorldPoint(mouse);
- //移动的物体的位置就等于转换成世界坐标的鼠标位置
- this.transform.position = mouseScreenPos;
- }
-
-
- }
复制代码 |
|