Unity中实现UI跟随

3D游戏中,有一种特殊的UI,那就是跟随游戏对象移动的UI(比如说名字,血条等)。本文主要实现了UI跟随。


实现思路

  1. 将游戏对象的世界坐标转化为屏幕坐标。
  2. 将跟随UI坐标与游戏对象屏幕坐标同步(或者同步一个差值)。
  3. 可以根据UI是否在屏幕上显示或关闭跟随的UI。
  4. 在实际项目中,跟随UI除了位置, 可能还会涉及缩放,是否显示(草丛等)等一些自定义同步操作。

血条跟随效果:


代码实现:

// 挂载在运动对象上
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {
    public float speed = 10f;
    Rigidbody rb;

    void Start () {
        rb = GetComponent<Rigidbody>();
    }   

    void FixedUpdate() {
        float h = Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        float v = Input.GetAxisRaw("Vertical") * speed * Time.deltaTime;
        rb.MovePosition(transform.position + new Vector3(h, 0, v));
    }
}
// 挂载在运动对象上

using UnityEngine;

public class UIFollow : MonoBehaviour {
    public Vector2 offset;
    public RectTransform rectTransform; // 跟随UI

    void Update() {
        Vector2 screenPos = Camera.main.WorldToScreenPoint(transform.position);
        rectTransform.position = screenPos + new Vector2(offset.x, offset.y);

        if (screenPos.x > Screen.width || screenPos.x < 0 || screenPos.y > Screen.height || screenPos.y < 0) 
            rectTransform.gameObject.SetActive(false);
        else 
            rectTransform.gameObject.SetActive(true);
    }

}

如有错误,欢迎指出。

email:dxmdxm1992#gmail.com

blog: http://blog.csdn.net/david_dai_1108

猜你喜欢

转载自blog.csdn.net/david_dai_1108/article/details/73698198