天降方块
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 76 课,共 85 课。
挑战
中等每秒在空中生成一个方块。保持操控功能不变。
- 添加
[SerializeField] private GameObject blockPrefab;、[SerializeField] private float spawnEvery = 1f;和private List<GameObject> blocks = new List<GameObject>();。 - 将
Time.deltaTime加到float timer上;当它达到spawnEvery时,从中减去spawnEvery。 - 然后在
new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f)处生成一个方块,并将它添加到blocks中。
按“运行”:方块会出现在跑道上方的高处。然后按“检查”。
亲手试试
using UnityEngine;
public class Runner : MonoBehaviour
{
[SerializeField] private float speed = 6f;
[SerializeField] private float laneEdge = 4f;
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;
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器