衝突でラン終了
CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 31/60。
チャレンジ
中級衝突すると、ランが停止するようにします。
GameManagerの上にpublic enum GameState { Playing, GameOver }を宣言し、その中にpublic GameState state = GameState.Playing;を追加します。public void GameOver()は、stateをGameState.GameOverに、speedを0に設定し、gameOverPanelを表示します。Runnerは、Obstacleタグが付いたトリガーに反応してGameManager.Instance.GameOver()を呼び出します。GameManager、Runner、Spawnerは、Playingでない場合にreturnする処理をUpdate()の冒頭に追加します。
「プレイ」を押して衝突させると、すべてが停止します。その後、「確認」を押します。
自分で試してみよう
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public float speed = 10f;
public float speedUp = 0.5f;
public float maxSpeed = 20f;
public TMP_Text distanceText;
public GameObject gameOverPanel;
public Button restartButton;
private float distance;
void Awake()
{
Instance = this;
}
void Update()
{
speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
distance += speed * Time.deltaTime;
distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
}
}
本格的なゲームを作るのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド