unity 2d 与3d坐标互相转换

时间:2022-02-24 04:19:51

// 根据3d的主角坐标,获得主角血条的坐标 (通过视窗坐标转换)

 Vector3 pos = cam.WorldToViewportPoint(Boy.position); // 将主角的3d坐标转换成对象屏幕的视窗坐标
UI.transform.position = UIcam.ViewportToWorldPoint(pos); // 根据视窗坐标获得UI血条在3d的位置

// 根据3d的主角坐标,获得主角血条的坐标 (通过屏幕坐标转换)

screenpos = _cameraScene.WorldToScreenPoint (target);
viewpos = _cameraUI.ScreenToWorldPoint (new Vector3 (screenpos.x,screenpos.y,_cameraUI.nearClipPlane));
viewpos.z = 0;
// 通过2d的坐标加上z轴的深度,获得该2d坐标在3d上的位置
    public static Vector3 PointVec2ToVec3(Vector2 vec2, float z){
Vector3 world = new Vector3 (vec2.x / Screen.width, vec2.y / Screen.height, z);
Vector3 world1 = Camera.main.ViewportToWorldPoint (new Vector3(world.x, world.y, world.z)); // 屏幕坐标转换成场景坐标
return world1;
}