Unity中Canvas下UI放在指定世界座標位置——最白話,手把手教你做系列。

描述:Unity場景中Canvas下UI座標轉世界座標
用於:有些遊戲會在3D搭建的遊戲場景中顯示一些Ui元素,但UI元素卻不能很好的匹配頁面。

後來發現Unity中還有這麼個方法

RectTransformUtility.ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);

描述:
屏幕空間點(Vector2 screenPoint)轉換爲矩形變換內部(RectTransform rect)的本地位置(out Vector2 localPoint),該點在它的矩形平面上。
用法比較多。
寫一個我用到的方法吧:

  public Canvas canvas;//指定的屏幕
//Vector3 point   世界座標點。
//RectTransform rect   UI位置。
//用於將某Ui位置顯示在指定的世界座標點的位置
    void setPosition(Vector3 point, RectTransform rect)
    {
        Vector2 pos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Camera.main.WorldToScreenPoint(point), canvas.worldCamera, out pos);
        rect.anchoredPosition = pos;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章