思路:给景物添加碰撞体后,写入对应脚本,再由角色触碰后调用脚本里改变透明度的函数
设置好对应的碰撞体。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YF71tmQy-1685852301727)(C:/Users/86188/AppData/Roaming/Typora/typora-user-images/image-20230604114215740.png)]](https://img-blog.csdnimg.cn/9a56cf6abff547799b0a35f7278e8c7b.png)
导入渐变的组件
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k5tdWRKE-1685852301730)(C:/Users/86188/AppData/Roaming/Typora/typora-user-images/image-20230604102812561.png)]](https://img-blog.csdnimg.cn/e14e59cef8e34e43b46cab1e23084312.png)
设置一下:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KXTPZuOQ-1685852301731)(C:/Users/86188/AppData/Roaming/Typora/typora-user-images/image-20230604102849706.png)]](https://img-blog.csdnimg.cn/46c310df03e641dfb22158822af06964.png)
统一一个集中存放设置的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Settings
{
public const float fadeDuration = 0.35f;
public const float targetAlpha = 0.45f;
}
渐变的类:
using DG.Tweening;
using UnityEngine;
//必须包含SpriteRenderer
[RequireComponent(typeof(SpriteRenderer))]
public class ItemFader : MonoBehaviour
{
private SpriteRenderer spriteRenderer;
private void Awake() {
spriteRenderer = GetComponent<SpriteRenderer>();
}
///<summary>
/// 逐渐恢复颜色
///<summary>
public void FadeIn(){
Color targetColor = new Color(1, 1, 1, 1);
spriteRenderer.DOColor(targetColor, Settings.fadeDuration);
}
///<summary>
/// 逐渐半透明
///<summary>
public void FadeOut(){
Color targetColor = new Color(1, 1, 1, Settings.targetAlpha);
spriteRenderer.DOColor(targetColor, Settings.fadeDuration);
}
}
玩家进入的判定:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerItemFader : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other) {
//遍历他下面所有包含ItemFader脚本的对象
ItemFader[] faders = other.GetComponentsInChildren<ItemFader>();
if(faders.Length > 0){
foreach (var item in faders) {
//将这些对象渐变
item.FadeOut();
}
}
}
private void OnTriggerExit2D(Collider2D other) {
//遍历他下面所有包含ItemFader脚本的对象
ItemFader[] faders = other.GetComponentsInChildren<ItemFader>();
if(faders.Length > 0){
foreach (var item in faders) {
//将这些对象变回去
item.FadeIn();
}
}
}
}
注意:玩家调用渐变类的方法。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-noEIIiVY-1685852301732)(C:/Users/86188/AppData/Roaming/Typora/typora-user-images/image-20230604121743724.png)]](https://img-blog.csdnimg.cn/cccbad91a5d2456b933d4ae0e93053c7.png)
完成!