当前位置:   article > 正文

Unity UI上的物体跟随场景物体位置变化而变化(人物血条/称号)_unity ui跟随物体

unity ui跟随物体

首先看下UI上物体的位置计算(UI上的物体 以下用“血条”代称)

这个很简单 无非就是坐标转换 把人物的世界坐标转到屏幕坐标
代码如下:

public Transform target;
    public Transform hpSp;
    public Camera mainCamera;


    void Update() {
        Vector3 pos11 = mainCamera.WorldToScreenPoint(target.position);
        hpSp.transform.localPosition = pos11;
    }

这时候我们运行程序 发现欸嘿 不对啊

这时候 我们发现血条并没有按照我们的想法出现在规定的位置
那么是什么原因导致的呢?
这时候我们发现血条(UI)的坐标系的中心点在屏幕的中间位置(ui坐标) 而我们屏幕的坐标系的中心点是左下角
于是我们需要做一下屏幕坐标转UI坐标
代码如下:

public Transform target;
    public Transform hpSp;
    public Camera mainCamera;


    void Update() {
        Vector3 pos = mainCamera.WorldToScreenPoint(target.position);
        //Screen.width和Screen.height分别为屏幕的宽的像素和屏幕的高的像素
        Vector3 pos1 = new Vector3(pos.x - Screen.width / 2, pos.y - Screen.height / 2, pos.z);
        hpSp.transform.localPosition = pos1;
    }

这时候我们运行程序之后发现血条到了我们规定的位置

这时候 我改动了 我的屏幕分辨率 由1280/720 改为1600/900 然后我发现血条的位置发生了轻微的改动 于是我做了下一步操作
代码如下:

public Transform target;
    public Transform hpSp;
    public Camera mainCamera;


    void Update() {
        Vector3 pos = mainCamera.WorldToScreenPoint(target.position);
        //Screen.width和Screen.height分别为屏幕的宽的像素和屏幕的高的像素
        Vector3 pos1 = new Vector3(pos.x - Screen.width / 2, pos.y - Screen.height / 2, pos.z);
        float scale = 1280f / Screen.width;
        Vector3 screenPos = new Vector3(pos1.x * scale, pos1.y * scale, 0.0f);
        hpSp.transform.localPosition = screenPos;
    }

 注: 我的 1280来源于这里

到了这里我觉得 血条挡在人脸上实在是难看 又懒得去找策划加血条位置的骨骼点 于是决定自己加一个血条距离人物的高度
代码如下:

public Transform target;
    public Transform hpSp;
    public Camera mainCamera;
    public Vector3 offsetPos;

    void Update() {
        Vector3 pos = mainCamera.WorldToScreenPoint(target.position+ offsetPos);
        //Screen.width和Screen.height分别为屏幕的宽的像素和屏幕的高的像素
        Vector3 pos1 = new Vector3(pos.x - Screen.width / 2, pos.y - Screen.height / 2, pos.z);
        float scale = 1280f / Screen.width;
        Vector3 screenPos = new Vector3(pos1.x * scale, pos1.y * scale, 0.0f);
        hpSp.transform.localPosition = screenPos;
    }

完整代码如下:

  1. public class test5 : MonoBehaviour {
  2. public Transform target;
  3. public Transform hpSp;
  4. public Camera mainCamera;
  5. public Vector3 offsetPos;
  6. void Update() {
  7. Vector3 pos = mainCamera.WorldToScreenPoint(target.position+ offsetPos);
  8. //Screen.width和Screen.height分别为屏幕的宽的像素和屏幕的高的像素
  9. Vector3 pos1 = new Vector3(pos.x - Screen.width / 2, pos.y - Screen.height / 2, pos.z);
  10. float scale = 1280f / Screen.width;
  11. Vector3 screenPos = new Vector3(pos1.x * scale, pos1.y * scale, 0.0f);
  12. hpSp.transform.localPosition = screenPos;
  13. }
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/111369
推荐阅读
相关标签
  

闽ICP备14008679号