博主大概08年开始接触电脑游戏,当时玩的是我哥的电脑,那时候家里没网,只可以玩电脑上自带的单机游戏,比如扫雷、蜘蛛纸牌等等,当然还有红色警戒、冰封王座、星际争霸、帝国崛起等等,这些大概是我哥当时在大学下载的,也是那个时候对游戏充满了兴趣,记忆很深刻那时候电脑上还有一款金山打字游戏,今天准备带大家来复刻一下这款游戏。
我们先来理一下思路,制作一款这样的游戏需要实现哪些功能,当然如果你没有玩过金山打字可以去各大视频网站先看一看。第一,实现字母下降速度随机;第二,随机区域生成随机字母;第三,当我们按下字母,字母销毁,没有按到,超出下界自动销毁;其他功能还包括:计分器、定时器、暂停菜单、音效等等,下面主要介绍实现主要功能的过程。
第一步,准备素材,包括背景图片(根据自己喜好)、字母样式(博主使用的是Asset Store免费素材105 Colorful 2D Planet Icons,找出26张图片,借助Photoshop,依次给每个图片P上26个字母,当然为实现功能,可以先拿3张图片,后续再进行添加),音效(根据自己在Asset Store下载即可)等等,新建文件夹,重命名,将素材导入unity,可以直接托人或者在项目文件存入,图片需修改Texture Type为Sprite(2D and UI),Pixels Per Unit设为188较为合适,如下图。
第二步,创建精灵 (GameObject > 2D Object > Sprites > Square ) ,将字母素材拖入Sprite Renderer中,注意:为了和背景区分图层,后续字母的图层排序都要大于背景图层,为了后续不搞混淆26个字母,建议重命名GameObject为相对应的字母。
第三步,给字母贴代码,新建C#文件,重命名为AlphabetController,双击打开cs文件,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AlphabetController : MonoBehaviour
{
public float speed;//定义下落速度
public string alphabet;//定义字母
public static int score = 0;//定义得分,静态变量,方便调用
// Start is called before the first frame update
void Start()
{
//speed = Random.Range(0.8f, 1.5f);//简单,随机速度生成
speed = Random.Range(3f, 5f); ;//中等,随机速度生成
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.down * Time.deltaTime * speed);//下落
if (Input.GetKeyDown(alphabet))//判断是否按下字母
{
Destroy(this.gameObject);//销毁字母
score++;//得分+1
}
if (transform.position.y < -3.5f)//判断是否超出下界
{
Destroy(this.gameObject);//销毁字母
}
}
}
第四步,在(Inspector)检视面板初始化字母,注意:上述代码判断只能识别小写字母,如下图,接着新建一个文件夹,重命名为Perfabs,用于存放预设体,将字母物体拖入文件内,即可生成预设体,重复以上操作,生成多个字母预设体,生成预设体后,可以删除层级面板的字母物体。
第五步,创建一个空物体(GameObject > Creat Enpty) ,新建C#文件,重命名为GameController,用于管理游戏,双击打开cs文件,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public GameObject[] card;//用于存放26个字母预设体
private float timer = 0;//定时器
public Text[] text;//用于存放计分器和定时器文本
public int count = 30;//定时器初始数字
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timer += Time.deltaTime;
if (timer > 1.5f)//生成字母时间间隔
{
CreateCard(Random.Range(0, card.Length));//随机生成字母
timer = 0;
}
Text();
Timing();
}
private void CreateCard(int index)//创造字母
{
float x = Random.Range(-4.5f, 4.5f);//定义横向生成区域
float y = Random.Range(1f, 4.5f);//定义纵向生成区域
Instantiate(card[index], new Vector3(x, y, 0), Quaternion.identity);//函数生成字母
}
public void Text()//计分器
{
text[0].GetComponent<Text>().text = "得分:" + AlphabetController.score; //显示
}
private float nextTime = 1;
private void Timing()//定时器
{
if (Time.time >= nextTime)
{
count -= 1;
nextTime = Time.time + 1;
}
if (count <= 0)//游戏结束
{
Time.timeScale = 0f;//运算时间处理变为0
}
text[1].GetComponent<Text>().text = "倒计时:" + count;//显示
}
}
第六步,在检视面板将字母预设体一个一个拖进Card,Text同理(记得先新建两个text),这样,一个类似于金山打字的小游戏就做好了,运行即可。