当前位置:   article > 正文

Unity UI跟随物体

unity ui跟随物体

体力条跟随主角

图上是体力条跟随着主角,主角左移,体力条就跟着左移。

首先我们需要知道主角单位对于屏幕

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

然后需要知道一开始UI和主角得屏幕相对位置之间得距离参数,利用这个参数就能使UI一直跟着主角。

offest.x = PlayerScreen.x - transform.position.x;
offest.z = PlayerScreen.z - transform.position.z;
offest.y = transform.position.y;
  • 1
  • 2
  • 3

Update里面一直获取主角对于屏幕的相对位置,然后在进行相减,就可以一直保持了。

 void Update()
    {
            PlayerScreen = Camera.main.WorldToScreenPoint(Player.transform.position);
            transform.position = PlayerScreen;
            transform.position = new Vector2(transform.position.x - offest.x, offest.y);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

不过我发现了,如果我在编辑器里面全屏运行,会出现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;
   }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

最后代码如下:

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/111379
推荐阅读
相关标签
  

闽ICP备14008679号