在游戏开发中,我们可能需要做到如下图所示的血条跟随效果

这是如何做到的呢?
我们就以这个血条举例,这个血条是UI下的Slider实现的。

我们可以为他创建一个Script,附着在Slider下。代码内容如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;//使用该命名空间实现UI下的各个功能
public class SliderController : HealthController
{
public Slider slider;//一个Slider对象,即SliderUI本身
public GameObject GameObject;//这里是Slider需要跟随的对象,比如上图所示的马
private void Update()
{
Vector2 healthSliderPosition = Camera.main.WorldToScreenPoint(GameObject.transform.position);//使用此方法将跟随物件的3维位置转化为屏幕上的2维位置
slider.GetComponent<RectTransform>().position = healthSliderPosition;//再将Slider的位置进行绑定
}
}
这个功能就顺利实现了,是不是很简单呢?