第三十七节 显示下一个方块
2019-06-25 本文已影响0人
安静的程序员
同样都是显示方块的屏幕,与ScreenMain几乎一样,所以类的实现原理就不详细讲解了,直接按步骤操作即可。
01.添加新类:ScreenAttached,完整代码请参考附件
using System.Collections.Generic;
using UnityEngine;
public class ScreenAttached : MonoBehaviour
{
public GameObject Pixel; // 像素点对象
GameObject[,] _screen; // 像素点数组
int _ScreenWidth = 4; // 屏幕宽度
int _ScreenHeight = 4; // 屏幕高度
int _ScreenPoint_x = 196; // 屏幕横坐标
int _ScreenPoint_y = 151; // 屏幕纵坐标
int _PixelSize = 14; // 像素点大小
int _PixelInterval = 1; // 像素点间距
List<Layer> _layerList; // 图层列表
List<MyPoint> _viewData; // 显示数据
// 初始化
public void Init()
{
_viewData = new List<MyPoint>();
InitScreen();
InitLayer();
}
...
02.在场景中添加新对象
添加空物体,命名为ScreenAttached,坐标归零。
03.添加脚本组件
将ScreenAttached脚本添加至空物体ScreenAttached上。
04.绑定像素点与导演
将预制体Pixel拖放至ScreenAttached的Pixel对象上,再将ScreenAttached拖动至导演对象的ScreenAttachedObj上,其实顺序无所谓。
05.通过导演初始化
在导演类添加对应的成员变量后,在InitGame()中初始化:
// 初始化附加屏幕
_screenAttachedScript = ScreenAttachedObj.GetComponent<ScreenAttached>();
if (_screenAttachedScript == null) return false;
_screenAttachedScript.Init();
06.下一个方块实现逻辑
首次启动时,需要生成两个方块:当前方块和下一个方块。
之后的逻辑为:
当前方块 = 下一个方块
下一个方块 = 新的下一个方块
07.添加下一个方块成员变量
其实就是添加一个类型即可:
EBlockType _nextBlockType; // 下一个方块的类型
08.添加生成下一个方块的逻辑
在InitGame()和CreateNewBlock()中添加生成下一个方块的代码:
InitGame():
// 生成下一个方块
_nextBlockType = BlockCreator.GetInstance().RandomBlockType();
_screenAttachedScript.GetLayer("DefaultLayer").ViewData = BlockCrea-tor.GetInstance().CreateBlock(_nextBlockType);
_screenAttachedScript.RefreshScreen();
CreateNewBlock():
// 生成方块
void CreateNewBlock()
{
_blockLayer.Point = new MyPoint(20, 4);
// 使用上一次生成的类型创建方块
_blockLayer.ViewData = BlockCreator.GetInstance().CreateBlock(_nextBlockType);
// 更新下一个方块
_nextBlockType = BlockCreator.GetInstance().RandomBlockType();
_screenAttachedScript.GetLayer("DefaultLayer").ViewData = BlockCrea-tor.GetInstance().CreateBlock(_nextBlockType);
_screenMainScript.RefreshScreen();
_screenAttachedScript.RefreshScreen();
}
运行结果:

代码链接:https://pan.baidu.com/s/1h99cG38vtk9bmJo_A-PEow
提取码:h91f