EnergyEfficiencyManagement/Assets/Zion/Scripts/Utils/HoverBreathingEffect.cs

130 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
/// <summary>
/// 鼠标悬停时物体呼吸效果的脚本
/// </summary>
public class HoverBreathingEffect : MonoBehaviour
{
[Header("呼吸灯设置")]
public Color breathColor = Color.cyan; // 呼吸灯颜色
public float breathSpeed = 1.7f; // 呼吸速度
[Range(0f, 1f)]
public float minIntensity = 0.2f; // 最小亮度
[Range(0f, 1f)]
public float maxIntensity = 0.8f; // 最大亮度
[Header("悬停触发设置")]
public float hoverDelay = 1.5f; // 悬停触发延时(秒)
private Material originalMaterial;
private Material breathMaterial;
private Renderer objectRenderer;
private bool isHovering = false;
private float hoverTimer = 0f;
private bool isBreathing = false;
private float breathPhase = 0f;
void Start()
{
// 获取渲染器和原始材质
objectRenderer = GetComponent<Renderer>();
if (objectRenderer != null)
{
originalMaterial = objectRenderer.material;
// 创建用于呼吸效果的新材质实例,避免影响其他物体
breathMaterial = new Material(originalMaterial);
objectRenderer.material = breathMaterial;
}
else
{
Debug.LogWarning("HoverBreathingEffect 需要 Renderer 组件。", this);
enabled = false;
}
}
void OnMouseEnter()
{
// 鼠标进入,开始计时
isHovering = true;
hoverTimer = 0f;
}
void OnMouseExit()
{
// 鼠标移出,重置所有状态
isHovering = false;
hoverTimer = 0f;
StopBreathing();
}
void Update()
{
HandleHoverTimer();
if (isBreathing)
{
UpdateBreathingEffect();
}
}
/// <summary>
/// 悬停时间计算
/// </summary>
void HandleHoverTimer()
{
if (isHovering && !isBreathing)
{
hoverTimer += Time.deltaTime;
if (hoverTimer >= hoverDelay)
{
// 达到延时,开始呼吸效果
StartBreathing();
}
}
}
/// <summary>
/// 开始出发呼吸灯效果
/// </summary>
void StartBreathing()
{
isBreathing = true;
breathPhase = 0f;
// 可以在这里触发音效或其他事件
// Debug.Log("开始呼吸效果: " + gameObject.name);
}
/// <summary>
/// 结束呼吸灯效果
/// </summary>
void StopBreathing()
{
if (isBreathing)
{
isBreathing = false;
// 恢复为原始材质颜色
if (breathMaterial != null && originalMaterial != null)
{
breathMaterial.color = originalMaterial.color;
}
}
}
/// <summary>
/// 刷新显示颜色
/// </summary>
void UpdateBreathingEffect()
{
// 使用正弦函数计算平滑的呼吸曲线
breathPhase += breathSpeed * Time.deltaTime;
float t = (Mathf.Sin(breathPhase) + 1f) * 0.5f; // 将范围映射到 0~1
float intensity = Mathf.Lerp(minIntensity, maxIntensity, t);
// 混合呼吸颜色和原始颜色
Color targetColor = Color.Lerp(originalMaterial.color, breathColor, intensity);
breathMaterial.color = targetColor;
// 如果也想影响自发光如果Shader支持可以取消注释下行
// breathMaterial.SetColor("_EmissionColor", targetColor * intensity);
}
}