FPS千锋丨资源、标签的封装和场景淡入淡出效果实现

2024-08-14 17:27:15 浏览数 (1)

将导入的场景“Demo”复制一份,重命名“FPS_QF”,并在该场景的合适位置添加Camera,完成如下操作

标签的封装

导入资源包后,新建Tags脚本,封装本游戏所有标签。内容如下

代码语言:javascript复制
using UnityEngine;

public class Tags : MonoBehaviour {

    public const string player = "Player";
    public const string gameController = "GameController";
    public const string enemy = "Enemy";
    //淡入淡出的画布
    public const string fader = "Fader";
    public const string mainCamera = "MainCamera";
}

屏幕渐隐渐现

1、新建空物体,重命名“FadeInOut”,位置归零

2、添加GUI Texture组件,将其颜色设置为黑色。搜索Assets,将swatch_black_dff赋值到其Texture上

3、新建“FadeInOut”脚本,并挂载到FadeInOut物体上,该脚本控制渐隐渐现效果的实现

代码语言:javascript复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class FadeInOut : MonoBehaviour {

    public float fadeSpeed = 1.5f;
    //表示该场景是否开始,若开始,让屏幕完成渐现效果
    private bool sceneStarting = true;
    private GUITexture tex;

    private void Start()
    {
        tex = GetComponent<GUITexture>();
        //设置tex画布的坐标和大小
        tex.pixelInset = new Rect(0, 0, Screen.width, Screen.height);
    }

    private void Update()
    {
        if (sceneStarting)
            StartScene();
    }

    //屏幕渐现
    private void StartScene()
    {
        FadeToClear();
        if (tex.color.a<0.05f)
        {
            tex.color = Color.clear;
            tex.enabled = false;
            sceneStarting = false;
        }
    }

    public void EndScene()
    {
        tex.enabled = true;
        FadeToBlack();
        if (tex.color.a > 0.95f)
        {
            tex.color = Color.black;
            SceneManager.LoadScene("FPS_QF");
        }
    }

    private void FadeToClear()
    {
        tex.color = Color.Lerp(tex.color, Color.clear, fadeSpeed * Time.deltaTime);
    }

    private void FadeToBlack()
    {
        tex.color = Color.Lerp(tex.color, Color.black, fadeSpeed * Time.deltaTime);
    }
}

效果展示

0 人点赞