Unity 实现物体拖拽

Unity实现拖拽:

也可以继承Unity EventSystem中的接口实现。

当鼠标按下的时候以左键为例:

   Using System.Collections;
Using System.Collections.Generic;
Using UnityEngine;   
public class Test:MonoBehavioout{     private Vector3 mousePos;//鼠标位置屏幕     private Vector3 targetPos;//目标位置     private Vector3 offect;//偏移位置鼠标转世界坐标与transform.position的偏移量     private Transform tran;//目标体Transform组件     void Awake(){       tran=transform;//获取Transform组件     }     Ienumerator OnMousedown{//Mono中的OnMouseDown可以改成协程       mousePos=new Vector3(Input.mousePosition.x,Input.mousePosition.y,tran.position.z);       offect=tran.position-Camera.main.ScreenToWorldPoint(mousePos);       while(Input.GetMouseButton(0)){         mousePos=new Vector3(Input.mousePosition.x,Input.mousePosition.y,tran.position.z);         targetPos=offect+Camera.main.ScreenToWorldPoint(mousePos);         tran.position=targetPos;         yield return new WaitForFixedUpdate();       }     }

 

当需要拖拽的物体是UI是,会阻挡射线检测即OnMouseDown等消息机制无法监听到,为了解决这个情况我们需要用到EventTrigger组件,用法类似给Button加上函数。

最重要的是对于UI使用的坐标并非transform组件而是rectTransform组件,故坐标为anchoredPosition才是UI的rect坐标。为了使鼠标坐标能够转换为rectPos坐标需要用到RectTransformUtility.ScreenPointToLocalPointInRectangle()函数,例子如下:

   using UnityEngine;
using System.Collections;   public class Test:MonoBehaviour{     Canvas canvas;//当前UI所在的画布     RectTransform rectTransform;     void Statr(){       rectTransform=transform as RectTransform;//将当transform组件转换为RectTransform       canvas=GameObject.Find(“Canvas”).GetComponent<Canvas>();
    }     
void Update(){       Vector2 Pos;       if(RectTransformUtility.ScreenPointToLocalPointInRectangle
(canvas.transform as RectTransform,Input.mousePosition,canvas.worldCamera,out pos))         rectTransform.anchoredPosition=pos;     }

其中rect 代表当前UI父对象的Rect,screecPoint代表需要转换成LocalPoint的屏幕坐标,cam代表渲染的相机,LocalPoint存储当前的LocalPos。若Canvas渲染模式为Overlay(叠加)模式cam为null。

转载于:https://www.cnblogs.com/dlvguo/p/9703949.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值