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坐标
代码如下:

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;
    }

完整代码如下:

public class test5 : MonoBehavIoUr {
    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;
    }
}

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...