Unity 开发日记教程 俄罗斯方块 (二)搭建方块UI和生成方块.

xiaoxiao2021-02-28  101

接前文.

本教程全部功能都使用Unity内置UGUI来完成,素材也仅使用其内置的5个默认素材.

首先,创建一个画布,根据要输出的显示器尺寸进行基本设置.

然后创建一个用于显示的正方形基本单元,并将其设置为预制体

然后创建2个脚本文件dmBlock和dmBlockBuilder,一个用来从方块数据中随机选取,并生成方块,一个用来保存已生成方块的正方形数据

然后写代码.

dmBlock的代码,主要用来保存将来生成的方形指针,以及该方块原始数据的指针备用

using System.Collections; using System.Collections.Generic; using UnityEngine; public class dmBlock { public List<GameObject> squareList = new List<GameObject>(); public dmBlockBase bindBase; public void InitBlock(dmBlockBase blockBase) { bindBase = blockBase; } }

dmBlockBuilder的代码,实现生成随机方块的功能

using System.Collections; using System.Collections.Generic; using UnityEngine; public class dmBlockBuilder : MonoBehaviour {     public List<dmBlockBase> blockBaseList;     public GameObject squarePrefab;     public Vector2 squareSize;     [HideInInspector]     public dmBlock nowBlock;     public void BuildRandomBlock()     {         if(nowBlock!=null)DestroySquares(nowBlock);         dmBlockBase inBuildingBlock = blockBaseList[Random.Range(0, blockBaseList.Count)];         nowBlock = new dmBlock();         nowBlock.InitBlock(inBuildingBlock);         foreach (Vector2 vec in inBuildingBlock.squareCoordList)         {             GameObject newSquare = Instantiate(squarePrefab);             newSquare.transform.SetParent(transform);             newSquare.transform.localPosition = new Vector3(squareSize.x * vec.x, -squareSize.x * vec.y);             newSquare.GetComponent<RectTransform>().sizeDelta = squareSize;             nowBlock.squareList.Add(newSquare);         }     }     public void DestroySquares(dmBlock block)     {         foreach(GameObject squareInstance in block.squareList)         {             Destroy(squareInstance);         }     } } 然后将dmBlockBuilder脚本与实体绑定,并配置数据(随机方块池,方形预制体,方形尺寸)

创建用于测试的按钮,并调用需要测试的方法(创建随机方块)

PLAY并测试

至此实现了创建随机方块的功能.

目录

(一) 定义方块

(二) 搭建方块UI和生成方块.

(三) 搭建场地UI和游戏流程控制

(四) 方块下落和落地判定

(五) 方块平移和旋转

(六) 方块消除

转载请注明原文地址: https://www.6miu.com/read-38136.html

最新回复(0)