阅读量:0
一,非URP
1,设置UICamera
将Canvas渲染模式改为Screen Space-Camera,并设置好摄像机
对应的摄像机设置为Depth Only,并且只渲染UI
2,制作好血条UI
3,在需要时创建血条,并设置好所属物体
hpBar = GameMgr_P1.S.InstantiatePrefab(PrefabType.HpBar); hpBar.transform.SetParent(GameObject.Find("Canvas").transform, false); hpBar.GetComponent<HpBar>().SetOwner(this.barPos);
4,血条更新位置
将目标点的世界坐标转换成屏幕坐标,之后使用RectTransformUtility.ScreenPointToWorldPointInRectangle函数转换为摄像机对应的世界空间中位于给定 RectTransform 平面上的一个位置
private void Update() { if (owner == null) return; Vector3 screenPos = Camera.main.WorldToScreenPoint(owner.position); Camera uiCamera = GameObject.FindWithTag("UICamera").GetComponent<Camera>(); if (RectTransformUtility.ScreenPointToWorldPointInRectangle( transform.parent as RectTransform, screenPos,uiCamera, out Vector3 worldPoint)) { transform.position = worldPoint; } }
二,URP
urp时相机没有depthonly模式,camera组件也有所变化
1,同样设置canvas渲染模式改为Screen Space-Camera,并设置好UI摄像机
2,相机的渲染模式改为overlay
3,主摄像机(渲染模式为base)的栈中添加ui摄像机
4,ui脚本相关同上