unity|Unity UI跟随物体

unity|Unity UI跟随物体
文章图片

图上是体力条跟随着主角,主角左移,体力条就跟着左移。
【unity|Unity UI跟随物体】首先我们需要知道主角单位对于屏幕

PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position);

然后需要知道一开始UI和主角得屏幕相对位置之间得距离参数,利用这个参数就能使UI一直跟着主角。
offest.x = PlayerScreen.x - transform.position.x; offest.z = PlayerScreen.z - transform.position.z; offest.y = transform.position.y;

Update里面一直获取主角对于屏幕的相对位置,然后在进行相减,就可以一直保持了。
void Update() { PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position); transform.position = PlayerScreen; transform.position = new Vector2(transform.position.x - offest.x, offest.y); }

不过我发现了,如果我在编辑器里面全屏运行,会出现UI靠的很近,我觉得非常奇怪,因为代码已经提前计算好了他们之间的距离,后面也是根据这个距离用来保持。
于是我发现,是因为一开始屏幕是小屏化的,Start一开始获取的offest差值是小屏时候的距离差,所以放大之后,UI就会靠的非常近,所以我就一时偷懒,直接一个协程,让他慢一秒在开始获取。
IEnumerator Wait() { yield return new WaitForSeconds(1f); Player = GameObject.FindGameObjectWithTag("Player").transform; PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position); offest.x = PlayerScreen.x - transform.position.x; offest.z = PlayerScreen.z - transform.position.z; offest.y = transform.position.y; IsRun = true; }

最后代码如下:
public class UIFollowShow : MonoBehaviour { private Transform Player; private Vector3 offest; private Vector3 PlayerScreen; private bool IsRun; // Start is called before the first frame update void Awake() { StartCoroutine(Wait()); }// Update is called once per frame void Update() { if (IsRun) { PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position); transform.position = PlayerScreen; transform.position = new Vector2(transform.position.x - offest.x, offest.y); } }IEnumerator Wait() { yield return new WaitForSeconds(1f); Player = GameObject.FindGameObjectWithTag("Player").transform; PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position); offest.x = PlayerScreen.x - transform.position.x; offest.z = PlayerScreen.z - transform.position.z; offest.y = transform.position.y; IsRun = true; } }

    推荐阅读