您当前的位置: 首页 >  游戏
  • 5浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 让UI位置跟随Sprite或其他游戏对象移动

我寄人间雪满头丶 发布时间:2020-06-22 17:45:00 ,浏览量:5

其实原理就是把Sprite的世界坐标转换为屏幕坐标,然后再把屏幕坐标转换为UI坐标,最后赋值给UI。只要掌握坐标系转换即可。 注意相机和Canvas不要用错。

public class UIFollowWorldObject : MonoBehaviour
{
    public Camera camera;
    public GameObject target;
    public bool alwaysFollow = true;

    bool hasFollowed = false;
    public Canvas canvas;

    public void Init()
    {
        FollowObject();
    }

    public void Update()
    {
        FollowObject();
    }

    void FollowObject()
    {
        if (!alwaysFollow && hasFollowed)
            return;

        if (camera != null && target != null)
        {
            Vector2 pos = camera.WorldToScreenPoint(target.transform.position);
            Vector2 point;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, pos, canvas.worldCamera, out point))
            {
                transform.localPosition = new Vector3(point.x, point.y, 0);
                hasFollowed = true;
            }
        }
    }
}
关注
打赏
1648518768
查看更多评论
立即登录/注册

微信扫码登录

0.1241s