Unity realizes the effect of blood bar slow down

translater

1. Create three new Image game objects and name them as BackGround, Mid, Front
Please add a picture description

2. Put an original image for the Mid and Front images, select the Image Type as Filled, set the Fill Mode (fill mode) as Horizontal (fill horizontally), and set the Fill origin (fill origin) as Left

Please add a picture description

Effect

Please add a picture description

the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HPUIDynamic : MonoBehaviour
{
    
    
    public float currentHP;
    public float maxHP;
    public float speed;

    [SerializeField] private Image mid;

    [SerializeField] private Image front;


    // Start is called before the first frame update
    void Start()
    {
    
    
        maxHP = 100f;
        currentHP = maxHP;

        front.fillAmount = currentHP;
        mid.fillAmount   = currentHP;
    }
    
    // Update is called once per frame
    void Update()
    {
    
    
        mid.fillAmount = Mathf.Lerp(mid.fillAmount, front.fillAmount, Time.deltaTime * speed);

        if(Input.GetKeyDown(KeyCode.Alpha1)){
    
    
            currentHP = Mathf.Clamp(currentHP - 10, 0, maxHP);
            front.fillAmount = currentHP / maxHP;
        }

        if(Input.GetKeyDown(KeyCode.Alpha2)){
    
    
            currentHP = Mathf.Clamp(currentHP + 10, 0, maxHP);
            front.fillAmount = currentHP / maxHP;
        }

    }
}

If you prefer video (I also learned this video) click here

Guess you like

Origin blog.csdn.net/blastospore/article/details/130692927