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()でtimeLeft > 0fの代わりにIsPlaying()を使い、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プレイグラウンド