当前位置:网站首页>Unity screen coordinates ugui coordinates world coordinates conversion between three coordinate systems

Unity screen coordinates ugui coordinates world coordinates conversion between three coordinate systems

2022-07-06 04:30:00 lifereset

First of all, understand a concept
UGUI Coordinate system , Take the center of the screen as the origin
Screen Coordinate system , Take the lower left corner of the screen as the origin

For example, you have a 3d object You want to add a blood bar to him And this blood bar is ugui The level in is very deep Then you can do this

var screenPoint = mainCamera.WorldToScreenPoint(this.hero.transform.position);
var localPosition = new Vector2();
UnityEngine.RectTransformUtility.ScreenPointToLocalPointInRectangle(this.blood.transform.parent as RectTransform, 
screenPoint, canvas.worldCamera, out localPosition);
this.blood.transform.localPosition = localPosition;

Camera.WorldToScreenPoint
This is yours position That is to say World coordinate system Convert to screen coordinates
And then call ScreenPointToLocalPointInRectangle Namely localPosition Coordinates

Transformation of three coordinate systems You can refer to this figure
 Insert picture description here
There are two classes WorldToScreenPoint Method
Camera Class has this method The return is Vector3
RectTransformUtility What comes back in the is Vector2

If you need h5 Inside globalToLocal perhaps localToGlobal
Then the following satisfies you
remember The camera is canvas Of

Vector2 localToGlobal(Transform transform , Vector2 vec2) 
{
    
        var screenPoint = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, transform.position);
        var GlobalPosition = new Vector2();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, 
        screenPoint, canvas.worldCamera, out GlobalPosition);
        return GlobalPosition + vec2;
}

Vector2 globalToLocal(Transform transform , Vector2 vec2 )
{
    
        var screenPoint = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, canvas.transform.position);
        var localPosition = new Vector2();
        UnityEngine.RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform, 
        screenPoint, canvas.worldCamera, out localPosition);
        return localPosition + vec2;
}

By the way
img9 Put it in canvas On the root of And set it to take the lower left corner as the origin
 Insert picture description here
Now
this.img9.transform.localPosition = new Vector2(0, 0);
So the picture is still canvas In the middle of the
because localPosition It doesn't matter where you set the origin
If you use the following sentence
this.img9.rectTransform.anchoredPosition = new Vector2(0, 0);
that img9 Just go to the lower left corner of the screen

原网站

版权声明
本文为[lifereset]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132220191282.html