unity如何制作屏幕闪红的效果?

介绍

unity如何制作屏幕闪红的效果?

在这里插入图片描述


方法

1.新建一张图片,颜色设置为红色,透明度设置为0。

2.挂载脚本

using UnityEngine;
using UnityEngine.UI;

public class Playerhealth : MonoBehaviour
{
    
    
    public Image hurtImage;
    private bool isDamage;
    private Color flashColor = new Color(1f, 0f, 0f, 1f);
    private Color clearColor = Color.clear;

    void Update()
    {
    
    
        if (isDamage)
        {
    
    
            hurtImage.color = flashColor;
        }
        else
        {
    
    
            hurtImage.color = Color.Lerp(hurtImage.color, clearColor, Time.deltaTime * 5);
        }

        isDamage = false;
    }

    public void OnAttack(int damage)
    {
    
    
        isDamage = true;

        if (damage <= 0) return;

        if (gameObject.CompareTag("Player"))
        {
    
    
            // 减少生命值
            // ...
        }

        if (gameObject.CompareTag("Enemy"))
        {
    
    
            // 减少敌人的生命值
            // ...
        }
    }
}

这段代码实现了玩家或敌人受到攻击时 hurtImage 颜色的闪烁效果。

代码主要分为两部分:

  1. Update() 方法用于每帧更新 hurtImage 的颜色。如果 isDamage 变量为 true,则将 hurtImage 的颜色设置为 flashColor,否则将其颜色渐变到 clearColor。最后将 isDamage 变量重置为 false

  2. OnAttack() 方法用于处理攻击事件。如果传入的 damage 值小于等于 0,则直接返回。如果当前对象的标签是 “Player”,则减少生命值;如果是 “Enemy”,则减少敌人的生命值。

最后,该脚本需要挂载到具有 Image 组件的游戏对象上,以便进行颜色变化。


猜你喜欢

转载自blog.csdn.net/qq_20179331/article/details/130717123