Menu
CoddyTech

与时间赛跑

本课属于 Coddy Unity 学习旅程的“物理与游戏玩法”单元。第 32 课,共 71 课。

challenge icon

挑战

中等

为 Coin Rush 添加一个计时器。

  1. 在 Ball.cs 中,添加 public float timeLimit = 60f; 和 public float timeLeft;;在 Start() 中设置 timeLeft = timeLimit;。
  2. 新增一个 Update(),当 timeLeft > 0f 时,从中减去 Time.deltaTime;当时间到 0 时,将其设为 0f,并记录 "Time's up! Score: " + score。
  3. 在 FixedUpdate() 中,仅当 timeLeft > 0f 时施加推力。

按“运行”,观察计时器。然后按“检查”。

亲手试试

using UnityEngine;

public class Ball : MonoBehaviour
{
    public float force = 10f;
    public int score;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        rb.AddForce(new Vector3(x, 0f, z) * force);
    }

    public void AddScore(int points)
    {
        score += points;
        Debug.Log("Score: " + score);
    }
}

物理与游戏玩法中的所有课

自己练习: Unity 在线编辑器