接上文.
我们拿到要操作的方块之后,事情就变得简单起来,只要用代码来控制现有的UI即可.
首先来实现方块下落.
我们首先需要定义一些字段来实现下落的功能.
fallspeed来控制方块下落速度,将来可以用来控制游戏的难易度.
runFlag用来表示游戏是否正在进行,可以用来做暂停功能,游戏结束等等.在游戏开始时将这个布尔量为真,暂停和gameover时为假.
fallInterval为下落时间间隔.
timeCount用来计游戏流逝时间,timeCount累积达到fallInterval时,使方块下落一格.
squareMap用来保存已经落地之后的正方形的位置.
[Range(1,10)]
public float fallSpeed;
RectTransform myRectTransform { get { return GetComponent<RectTransform>(); } }
dmBlock nowControlBlock;
bool runFlag;
float fallInterval { get { return 1 / fallSpeed; } }
float timeCount;
Vector2 nowBlockPos;
Dictionary<Vector2, GameObject> squareMap = new Dictionary<Vector2, GameObject>();
重构StartGame
public void StartGame()
{
if (nowControlBlock != null)
{
blockBuilder.DestroySquares(nowControlBlock);
}
if(squareMap != null)
{
foreach(Vector2 squareCoord in squareMap.Keys)
{
Destroy(squareMap[squareCoord]);
}
}
squareMap.Clear();
blockBuilder.BuildRandomBlock();
NextBlock();
timeCount = 0;
runFlag = true;
}
回收上次游戏的残留正方形,然后初始化一些控制用变量的初始值
写Update函数,Unity每一帧会自动调用Update,我们要把帧转换成固定时间,用timeCount变量的累计来做
void Update () {
if (runFlag)
{
timeCount += Time.deltaTime;
if