﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

//跟随3D物体的UI
public class FollowItem : MonoBehaviour
{
    private Canvas can;
    private GameObject target;
    private Text text;
    private float offset;
    private void Start() {
        can = transform.root.GetComponent<Canvas>();

        #region TEST
        Init(GameObject.Find("Sphere"),"球体",1f);
        #endregion
    }

    private void Update() {
        if(target)
        {
            World2UI(target.transform.position);
        }
    }

    public void Init(GameObject target,string name,float offset)
    {
        this.target = target;
        text = transform.Find("Text").GetComponent<Text>();
        text.text = name;
        this.offset = offset;
    }

    private void World2UI(Vector3 wPos)
    {
        Vector3 dir = wPos - Camera.main.transform.position;
        float dot = Vector3.Dot(dir,Camera.main.transform.forward);
        if(dot<0)
        {
            GetComponent<RectTransform>().anchoredPosition = new Vector2(10000,10000);
            return;
        }
        Vector2 tempV2 = Vector2.zero;
        Vector3 spos  = Camera.main.WorldToScreenPoint(wPos+Vector3.up*offset);
        tempV2.Set(spos.x,spos.y);
        Vector2 rePos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(can.GetComponent<RectTransform>(),
        tempV2,can.worldCamera,out rePos);
        rePos += Vector2.up*100f;
        GetComponent<RectTransform>().anchoredPosition = rePos;
    }
}
