让它们落下
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 77 课,共 85 课。
挑战
中等让列表中的每个方块都下落。保留之前步骤中的所有内容。
- 添加
[SerializeField] private float fallSpeed = 5f;。 - 在
Update()的末尾,用foreach (GameObject block in blocks)循环。 - 在循环中,将
Vector3.down * fallSpeed * Time.deltaTime加到block.transform.position上。
按“开始”:方块会从跑步者身边落下。然后按“检查”。
亲手试试
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;
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));
}
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器