Menu
CoddyTech

負け

CoddyのUnityジャーニー「物理演算とゲームプレイ」セクションの一部。レッスン 34/71。

このステップでCoin Rushが完成します。力で押されるボール、トリガーとして機能するコイン、1つのスクリプトで管理するスコア、そしてゲームを終了させる時計を作ります。

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プレイグラウンド