Unity 實現物體拖拽

Unity實現拖拽:canvas

也能夠繼承Unity EventSystem中的接口實現。函數

當鼠標按下的時候以左鍵爲例:spa

   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加上函數。code

最重要的是對於UI使用的座標並不是transform組件而是rectTransform組件,故座標爲anchoredPosition纔是UI的rect座標。爲了使鼠標座標可以轉換爲rectPos座標須要用到RectTransformUtility.ScreenPointToLocalPointInRectangle()函數,例子以下:orm

   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。協程

相關文章
相關標籤/搜索