Menu
CoddyTech

你输了

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

这一步将完成 Coin Rush:一个受力推动的小球、作为触发器的金币、由一个脚本记录的分数,以及一个会结束游戏的计时器。

challenge icon

挑战

中等

先在时间结束时告诉玩家。

  1. 在 Ball.cs 的 Update() 中,找到输出 Time's up! 的那一行。
  2. 紧接着在它后面输出 You lose!。

按“开始”,让计时结束:控制台会先显示 Time's up! Score: 0,然后显示 You lose!。接着按“检查”。

亲手试试

using UnityEngine;

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

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

    void Update()
    {
        if (IsPlaying())
        {
            timeLeft -= Time.deltaTime;
            if (timeLeft <= 0f)
            {
                timeLeft = 0f;
                Debug.Log("Time's up! Score: " + score);
            }
        }
    }

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

    public void AddScore(int points)
    {
        if (!IsPlaying())
        {
            return;
        }
        score += points;
        Debug.Log("Score: " + score);
        if (score >= target)
        {
            Debug.Log("You win!");
        }
    }

    bool IsPlaying()
    {
        return timeLeft > 0f && score < target;
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

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

自己练习: Unity 在线编辑器