Menu
CoddyTech

道路交通

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 83 课,共 85 课。

challenge icon

挑战

困难

让汽车沿着道路行驶。

  1. 每隔 spawnEvery 秒,在 (-9, 0.5, lanes[Random.Range(0, lanes.Length)]) 处生成一辆汽车,并将它加入列表。
  2. 让每辆汽车沿 +x 方向移动,速度为 carSpeed;超过 x = 9 后,销毁并移除它。
  3. 如果一辆汽车在 x 方向距离小于 1.5,且在 z 方向距离小于 1,就记录 Hit!,并让角色返回 start。

按“开始”:汽车会不断驶过。然后点击“检查”。

亲手试试

using System.Collections.Generic;
using UnityEngine;

public class Crossing : MonoBehaviour
{
    [SerializeField] private GameObject carPrefab;
    [SerializeField] private float[] lanes;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float carSpeed = 5f;

    private Vector3 start;

    void Start()
    {
        start = transform.position;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            transform.position += new Vector3(0f, 0f, 2f);
        }
        if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.z > start.z)
        {
            transform.position -= new Vector3(0f, 0f, 2f);
        }
        if (transform.position.z >= 4f)
        {
            Debug.Log("You made it!");
            enabled = false;
            return;
        }

        // 汽车:下一课再讲。
    }
}

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器