Menu
CoddyTech

你赢了

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

challenge icon

挑战

中等

让玩家在达到 target 分时获胜。

  1. 在 Ball.cs 中,添加 public int target = 10; 和 bool IsPlaying(),让它返回 timeLeft > 0f && score < target。
  2. 在 Update() 和 FixedUpdate() 中使用 IsPlaying() 替代 timeLeft > 0f,并让 AddScore 以 if (!IsPlaying()) return; 开头。
  3. 在分数语句之后,当 score >= target 时,记录 You win!。

按下“开始”并收集 8 分,然后点击“检查”。

亲手试试

using UnityEngine;

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

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

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

    void FixedUpdate()
    {
        if (timeLeft > 0f)
        {
            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 在线编辑器