In 3D games, there is a special kind of UI, that is, the UI that moves with the game object (such as name, health bar, etc.). This article mainly implements UI follow.
Realize ideas
- Convert the game object's world coordinates to screen coordinates.
- Synchronizes following UI coordinates with game object screen coordinates (or a delta).
- The UI that follows can be displayed or closed depending on whether the UI is on screen.
- In actual projects, in addition to the position of the UI, it may also involve some custom synchronization operations such as zooming, whether to display (grass, etc.).
Health bar follow effect:
Code:
// 挂载在运动对象上
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);
}
}
If there are any mistakes, please point them out.
email:dxmdxm1992#gmail.com