勝つか負けるか
CoddyのUnityジャーニー「物理演算とゲームプレイ」セクションの一部。レッスン 32/63。
チャレンジ
中級最後のステップ:勝利する方法です。これまでのステップの内容をすべて残し、Ballに次を追加します。
public int target = 10;(Inspectorで8に設定します)。timeLeftが0より大きく、scoreがtargetより小さい間、ゲームは進行中です。これをメソッドbool IsPlaying()として記述し、使用します。ゲーム進行中のみ、時計がカウントダウンし、矢印キーでボールを動かせて、コインでスコアが加算されます。- コインによって
scoreがtarget以上になったら、スコアの行の後にYou win!をログに出力します。 - 先に時間切れになった場合は、
Time's up!の行の後にYou lose!をログに出力します。
Playを押し、時間切れになる前に8ポイントに到達してから、Checkを押します。
自分で試してみよう
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);
}
}