using unityengine;
using unityengine.eventsystems;
public class screentouiconverter : monobehaviour
{
public recttransform targetparentrect; // 目标ui父物体的recttransform
void update()
{
vector2 mousepos = input.mouseposition; // 获取鼠标位置(屏幕坐标)
camera canvascam = null; // 如果canvas的渲染模式为screen space - overlay,camera设置为null
// 将屏幕坐标转换为ui坐标
vector2 localpoint;
if (recttransformutility.screenpointtolocalpointinrectangle(targetparentrect, mousepos, canvascam, out localpoint))
{
debug.log("ui坐标: " + localpoint);
}
}
}
另一种:
// 将屏幕坐标转换为世界坐标
vector3 worldpoint = mcamera.screentoworldpoint(new vector3(screenpoint.x, screenpoint.y, mcamera.nearclipplane));
// 将世界坐标转换为本地坐标
vector3 localpoint = root.transform.inversetransformpoint(worldpoint);
发表评论