天天看点

UGUI 和世界坐标的转换

需求一 :让UGUI中的UI随着场景中的模型位置而移动,类似人物血条,这里需要移动的是UI

需求二:让场景中的模型位置随着UI移动而变化,这里移动的是模型位置。

这两个需求正是对UGUI和世界坐标的转换的应用。

当canvas的render模式是overlay的时候,这个时候只有一个相机,即世界相机,没有所谓UI相机,ui坐标就是屏幕坐标。

     Transform target;//模型

    Camera worldcamera;//世界相机

    RectTransform m_ui;//ui

    RectTransform m_canvas;//ui canvas

一 解决需求一:

    vector3 screenpos = worldcamera.WorldToScreenPoint(target.position);//把模型坐标转为屏幕坐标

    vector2 temp = vector2.zero;

    vector2 uipos= vector2.zero;

    temp.set(screenpos.x,screenpos.y);

   RectTransformUtility.ScreenPointToLocalPointInRectangle(m_canvas, //需要求取的ui所在的canvas

          temp,//屏幕坐标

          null, //因为是overlay所有不存在相机

          out uipos);//把屏幕坐标转为ui坐标

   m_ui.anchoredPosition = uipos;

二 解决需求二:

    变量如上

    vector3 worldpos;

    temp.set(m_ui.position.x,m_ui.position.y);

    RectTransformUtility.ScreenPointToWorldPointInRectangle(m_canvas, //ui所在的canvas

          temp,//屏幕坐标

          worldcamera, //求取渲染模型所用的相机

          out worldpos);//ui对应的模型坐标

  target.position = worldpos;

当canvas的render模式是camera的时候,只需要把解决需求一中的null换成UI相机即可。

继续阅读