效果:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
class Test : MonoBehaviour
{
public Image hp;
public Image hurt;
public float harm = 0.1f;
public float speed = 0.01f;
float startTime;
void Start()
{
//血量初始化
hurt.fillAmount= hp.fillAmount = 1f;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.J))
{
hp.fillAmount -= harm;
//Time.time 帧开始的时间(只读)
startTime = Time.time;
}
if (hurt.fillAmount!= hp.fillAmount)
{
//Lerp(开始值,结束值,每次扣血的百分比) 当开始值趋向于结束值时,扣血速度会越来越慢 通过 当前时间减去开始扣血的时间*扣血百分比来解决
hurt.fillAmount = Mathf.Lerp(hurt.fillAmount,hp.fillAmount, (Time.time - startTime)*speed);
}
}
}