介绍
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
颜色的闪烁效果。
代码主要分为两部分:
-
Update()
方法用于每帧更新hurtImage
的颜色。如果isDamage
变量为true
,则将hurtImage
的颜色设置为flashColor
,否则将其颜色渐变到clearColor
。最后将isDamage
变量重置为false
。 -
OnAttack()
方法用于处理攻击事件。如果传入的damage
值小于等于 0,则直接返回。如果当前对象的标签是 “Player”,则减少生命值;如果是 “Enemy”,则减少敌人的生命值。
最后,该脚本需要挂载到具有 Image
组件的游戏对象上,以便进行颜色变化。