unity2d人物头顶设置血条实现
ui->image//加入ui图片显示
拖入白色血条图片,设置width200,height20
image tape 设置为filled
颜色设置为红色
注意!!!!这里按着alt建选择middle的靠左边的那个,因为这是设置锚点,最左边之后我们可以通过设置width让血量减少
复制粘贴一份形成两个image节点,另一个颜色为白色,作为底下的背景
创建ui->按钮,然后让按钮的位置大小和血条一样,方便我们后面设计鼠标点击后血量减少
记得设置透明度为0,让按钮不显示
创建c#代码,命名xuetiao,内容如下
public class xuetiao : MonoBehaviour
{
// Start is called before the first frame update
public GameObject my;
public float speed = 5.0f;
bool conctol = false;
void Start()
{
my.GetComponent<Button>().onClick.AddListener(delegate ()
{
conctol =true;
}
);
}
// Update is called once per frame
void Update()
{
if (conctol)
StartCoroutine(Changeblood());
}
IEnumerator Changeblood()
{
yield return null;//停止执行方法time秒,下一帧从这里开始return new waitforsecong(time);
this.GetComponent<RectTransform>().sizeDelta = Vector2.Lerp(this.GetComponent<RectTransform>().sizeDelta, new Vector2(0, this.GetComponent<RectTransform>().sizeDelta.y), speed * Time.deltaTime/10.0f );
}
}
*lerp是一个插入值的函数Lerp 插值
static functionLerp (from : Vector2, to : Vector2, t : float) : Vector2
两个向量之间的线性插值。按照数字t在form到to之间插值。
t是夹在0到1之间。当t=0时,返回from。当t=1时,返回to。当t=0.5时放回from和to之间的平均数。*
代码加到红的血条上面
这里拖进去刚才的按钮组件
然后运行,点击血条,会看到血条逐渐下降