unity獲取ugui上鼠標位置


public class GetMousePos : MonoBehaviour
{
    public Canvas canvas;//畫布
    private RectTransform rectTransform;//坐標

    void Start()
    {
        canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        rectTransform = canvas.transform as RectTransform; //也可以寫成this.GetComponent<RectTransform>(),但是不建議;

    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 pos;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, Input.mousePosition, canvas.worldCamera, out pos))
            {
                rectTransform.anchoredPosition = pos;
                Debug.Log(pos);
            }
        }
    }
}

  新建場景,在場景中拖一個畫布(Canvas),然后隨便找個地方掛上這個腳本就好了。

  RectTransformUtility:矩陣變換工具

  RectTransformUtility.ScreenPointToLocalPointInRectangle 從屏幕點到矩形內的本地點

Parameters 參數

rect The RectTransform to find a point inside.
cam The camera associated with the screen space position.
screenPoint Screen space position.
localPoint Point in local space of the rect transform.

Returns

bool Returns true if the plane of the RectTransform is hit, regardless of whether the point is inside the rectangle.

Description 描述

Transform a screen space point to a position in the local space of a RectTransform that is on the plane of its rectangle.

屏幕空間點轉換為矩形變換內部的本地位置,該點在它的矩形平面上。

The cam parameter should be the camera associated with the screen point. For a RectTransform in a Canvas set to Screen Space - Overlay mode, the cam parameter should be null.

該cam 參數應該是該相機關聯的屏幕點。對於在畫布上的矩形變換設置該屏幕空間為-Overlay模式,cam 參數應該為空。

When ScreenPointToLocalPointInRectangle is used from within an event handler that provides a PointerEventData object, the correct camera can be obtained by using PointerEventData.enterEventData (for hover functionality) or PointerEventData.pressEventCamera (for click functionality). This will automatically use the correct camera (or null) for the given event.

當ScreenPointToLocalPointInRectangle從事件處理器內部提供一個PointerEventData對象被使用時,相機可以通過使用PointerEventData.enterEventData(為懸停功能)或者 PointerEventData.pressEventCamera(為單擊功能)被獲取。該函數將會自動對指定事件使用正確的相機(或者空)。 

 

RectTransform矩形變換

RectTransform.anchoredPosition 錨點位置

The position of the pivot of this RectTransform relative to the anchor reference point.

該矩形變換相對於錨點參考點的中心點位置。

The anchor reference point is where the anchors are. If the anchors are not together, the four anchor positions are interpolated according to the pivot placement.

錨點參考點是錨點的位置。如果錨點不在一起,四個錨點的位置是根據布置的中心點的位置插值替換的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM