110 lines
3.1 KiB
C#
110 lines
3.1 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class VaultWall : MonoBehaviour
|
|
{
|
|
// 在这个标志控制是否可以翻越
|
|
public bool isPlayerInRange = false;
|
|
|
|
public GameObject Sigh; // 父物体,包含两个 Quad 的父级对象
|
|
public float blinkSpeed = 2.0f; // 控制闪烁的速度
|
|
|
|
private Material[] sighMaterials; // 子物体的材质
|
|
private Color[] originalColors; // 保存每个子物体的原始颜色
|
|
|
|
private bool isBlinking = false;
|
|
private Coroutine blinkCoroutine; // 用于保存协程的句柄
|
|
|
|
private void Start()
|
|
{
|
|
// 获取子物体的 MeshRenderer 组件
|
|
MeshRenderer[] renderers = Sigh.GetComponentsInChildren<MeshRenderer>();
|
|
|
|
if (renderers.Length > 0)
|
|
{
|
|
// 初始化材质和颜色数组
|
|
sighMaterials = new Material[renderers.Length];
|
|
originalColors = new Color[renderers.Length];
|
|
|
|
for (int i = 0; i < renderers.Length; i++)
|
|
{
|
|
sighMaterials[i] = renderers[i].material; // 实例化材质,确保每个子物体的材质独立
|
|
originalColors[i] = sighMaterials[i].color; // 保存每个子物体的原始颜色
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("No MeshRenderer found in the children of Sigh.");
|
|
}
|
|
}
|
|
|
|
// 当角色进入触发区域时
|
|
private void OnTriggerEnter(Collider other)
|
|
{
|
|
if (other.CompareTag("Player")) // 确保检测的是角色
|
|
{
|
|
isPlayerInRange = true;
|
|
StartBlinking(); // 当玩家进入范围时开始闪烁
|
|
}
|
|
}
|
|
|
|
// 当角色离开触发区域时
|
|
private void OnTriggerExit(Collider other)
|
|
{
|
|
if (other.CompareTag("Player"))
|
|
{
|
|
isPlayerInRange = false;
|
|
StopBlinking(); // 当玩家离开范围时停止闪烁
|
|
}
|
|
}
|
|
|
|
public void StartBlinking()
|
|
{
|
|
if (!isBlinking) // 防止重复启动协程
|
|
{
|
|
isBlinking = true;
|
|
blinkCoroutine = StartCoroutine(BlinkAlpha());
|
|
}
|
|
}
|
|
|
|
public void StopBlinking()
|
|
{
|
|
if (isBlinking) // 防止重复停止协程
|
|
{
|
|
isBlinking = false;
|
|
if (blinkCoroutine != null)
|
|
{
|
|
StopCoroutine(blinkCoroutine); // 使用协程句柄安全停止
|
|
}
|
|
|
|
// 还原所有子物体的原始颜色
|
|
for (int i = 0; i < sighMaterials.Length; i++)
|
|
{
|
|
sighMaterials[i].color = originalColors[i];
|
|
}
|
|
}
|
|
}
|
|
|
|
private IEnumerator BlinkAlpha()
|
|
{
|
|
float elapsedTime = 0f;
|
|
|
|
while (isBlinking)
|
|
{
|
|
// 使用 Mathf.Sin 使 Alpha 在 0 到 1 之间平滑渐隐渐显
|
|
elapsedTime += Time.deltaTime * blinkSpeed;
|
|
float alphaValue = (Mathf.Sin(elapsedTime) + 1) / 2; // sin 的结果在 -1 和 1 之间,转换到 0 到 1 之间
|
|
|
|
for (int i = 0; i < sighMaterials.Length; i++)
|
|
{
|
|
Color color = sighMaterials[i].color;
|
|
color.a = alphaValue; // 平滑修改 Alpha 值
|
|
sighMaterials[i].color = color;
|
|
}
|
|
|
|
yield return null; // 等待下一帧
|
|
}
|
|
}
|
|
}
|