障碍物
Coddy Unity 游戏:天空赛道 课程的第 9 课,共 21 课。
现在,路面上需要有东西可以躲避。每一段路面中间都会在随机车道上生成一个障碍物。由一个名为 Fill 的方法来完成这件事:在 Start 中为每一段新路面调用它,每当一段路面回到前方时也会再次调用。
前两段路面保持空白,给玩家一点反应时间:Road 会通过 made 记录已填充的路面段数。
void Fill(Transform chunk)
{
made++;
if (made <= safeChunks) return;
int lane = Random.Range(-1, 2);
Place(chunk, barrierPrefab, lane, 0.5f, 0f);
}Random.Range(-1, 2) 会返回 -1、0 或 1:对于整数,第二个数字永远不会被选中。
回收的路面段仍然带着旧障碍物。Clear 会销毁所有带有标签的子对象。地面、虚线和边缘都没有标签,所以会保留下来:
void Clear(Transform chunk)
{
foreach (Transform child in chunk)
{
if (!child.CompareTag("Untagged")) Destroy(child.gameObject);
}
}挑战
简单在每段道路上放置一个障碍物。
- 在
Road中添加public GameObject barrierPrefab;、public int safeChunks = 2;和private int made;。 - 编写
Place(chunk, prefab, lane, y, z):将预制件放在chunk.position + new Vector3(lane * laneWidth, y, z)处,使用prefab.transform.rotation,并将其设为这段道路的子对象。 - 按照上面的内容编写
Fill和Clear。 - 在 Start 中为每段道路调用
Fill(chunk),并在某段道路移动到最前面时调用Clear(chunk); Fill(chunk);。
按下“开始”:前两段道路之后的每段道路上,都会有一个红色障碍物出现在随机车道中。然后点击“检查”。
亲手试试
using UnityEngine;
public class Runner : MonoBehaviour
{
public float laneWidth = 2.5f;
public float laneSpeed = 16f;
public float jumpHeight = 1.6f;
public float gravity = -40f;
public float slideTime = 0.7f;
public int lane;
private CharacterController controller;
private float fallSpeed;
private float slide;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) lane = Mathf.Max(-1, lane - 1);
if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) lane = Mathf.Min(1, lane + 1);
bool jump = Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space);
if (jump && controller.isGrounded)
{
fallSpeed = Mathf.Sqrt(jumpHeight * -2f * gravity);
StopSlide();
}
if ((Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) && controller.isGrounded)
{
slide = slideTime;
Resize(0.5f);
}
if (slide > 0f)
{
slide -= Time.deltaTime;
if (slide <= 0f) StopSlide();
}
if (controller.isGrounded && fallSpeed < 0f) fallSpeed = -2f;
fallSpeed += gravity * Time.deltaTime;
float targetX = lane * laneWidth;
float x = Mathf.MoveTowards(transform.position.x, targetX, laneSpeed * Time.deltaTime);
Vector3 move = new Vector3(x - transform.position.x, fallSpeed * Time.deltaTime, 0f);
controller.Move(move);
}
void StopSlide()
{
if (transform.localScale.y < 1f) Resize(1f);
slide = 0f;
}
void Resize(float height)
{
controller.enabled = false;
transform.position += Vector3.up * (height - transform.localScale.y);
transform.localScale = new Vector3(1f, height, 1f);
controller.enabled = true;
}
}
Unity 游戏:天空赛道中的所有课
自己练习: Unity 在线编辑器