Unity3D 血条的渐变效果

Unity3D 血条的渐变效果

  • 效果图
  • 一、准备工程项目
  • 二、新建脚本
    • 1.新建test脚本挂在BG上
    • 2.新建Player脚本挂在Player上
  • 总结


效果图

此效果可结合多层血条特效,效果更佳
点击此处可查看多层血条特效 添加链接描述
Unity3D 血条的渐变效果_第1张图片

提示:以下是本篇文章正文内容,下面案例可供参考

一、准备工程项目

Unity3D 血条的渐变效果_第2张图片

二、新建脚本

1.新建test脚本挂在BG上


using UnityEngine;
using UnityEngine.UI;

namespace HKZ
{
    public class Test : MonoBehaviour
    {
        public static Test Instance;
        private Image imgRed;
        private Image imgYellow;
        private float currentPrg = 1f;
        private float targetPrg = 1f;

        public float AccelerHpSpeed = 0.5f;//渐变速度

        private void Start()
        {
            Instance = this;
            imgRed = transform.Find("imgRed").GetComponent<Image>();
            imgYellow = transform.Find("imgYellow").GetComponent<Image>();
            imgRed.fillAmount = 1;
            imgYellow.fillAmount = 1;
        }

        private void Update()
        {
            BlendHp();
            imgYellow.fillAmount = currentPrg;
        }

        public void SetHpVal(int oldVal, int newVal, int sum)
        {
            currentPrg = oldVal * 1.0f / sum;
            targetPrg = newVal * 1.0f / sum;
            imgRed.fillAmount = targetPrg;
        }

        private void BlendHp()
        {
            if (Mathf.Abs(currentPrg - targetPrg) < AccelerHpSpeed * Time.deltaTime)
            {
                currentPrg = targetPrg;
            }
            else if (currentPrg > targetPrg)
            {
                currentPrg -= AccelerHpSpeed * Time.deltaTime;
            }
            else
            {
                currentPrg += AccelerHpSpeed * Time.deltaTime;
            }
        }
    }
}

2.新建Player脚本挂在Player上

代码如下(示例):

using UnityEngine;

namespace HKZ
{
    public class Player : MonoBehaviour
    {
        private int hp = 1000;
        private int oldHp;
        private int newHp;
        private int hurt = 300;

        private void Start()
        {
            oldHp = hp;
        }

        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                newHp = oldHp - hurt;
                Test.Instance.SetHpVal(oldHp, newHp, hp);
                oldHp = newHp;
            }
        }
    }
}

总结

Unity3D 血条的渐变效果_第3张图片

你可能感兴趣的:(Unity3D,unity3d,ugui,c#)