生存并得分
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 80 课,共 85 课。
这一步将完成《躲避方块》:添加一个计时器来生成方块、一个会移动并清理方块的列表、碰撞检测,以及一个按秒计数的分数。浮点数前面的 (int) 会去掉小数部分。
挑战
中等添加分数,并让方块越落越快。
- 添加
private float score;和[SerializeField] private float speedUp = 0.2f;。 - 在
Update()的开头,将Time.deltaTime加到score,并将speedUp * Time.deltaTime加到fallSpeed。 - 碰撞时,记录
"Game over! Score: " + (int)score。(int)会舍去小数部分:12.7 会显示为 12。
按“开始”并努力存活:碰撞时会记录你的分数。然后点击“检查”。
亲手试试
using System.Collections.Generic;
using UnityEngine;
public class Runner : MonoBehaviour
{
[SerializeField] private float speed = 6f;
[SerializeField] private float laneEdge = 4f;
[SerializeField] private GameObject blockPrefab;
[SerializeField] private float spawnEvery = 1f;
[SerializeField] private float fallSpeed = 5f;
private List<GameObject> blocks = new List<GameObject>();
private float timer;
void Update()
{
Vector3 p = transform.position;
p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
transform.position = p;
timer += Time.deltaTime;
if (timer >= spawnEvery)
{
timer -= spawnEvery;
Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
}
for (int i = blocks.Count - 1; i >= 0; i--)
{
blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
Vector3 b = blocks[i].transform.position;
if (Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f)
{
Debug.Log("Game over");
enabled = false;
return;
}
if (b.y < -1f)
{
Destroy(blocks[i]);
blocks.RemoveAt(i);
}
}
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器