「簡単なパックマン風のゲーム」をUnityで作成する、第4回目です。
はじめに
Part1は下記になります。
Part1ではプレイヤーの移動を作成、Part2ではステージを作成、Part3では敵キャラを作成しました。
今回はアイテムを設置し、ゲームクリアとゲームオーバーを実装して仮の完成形にしていきます。
作成開始
プレイヤーが触れたら回収するアイテムを作成した後、ゲームクリアを作成していきます。
アイテムの作成
アイテムは下記画像を利用していきます。

Unityに取り込み、画像の設定をします。

Hierarchyにドラッグアンドドロップして、「BoxCollider2D」をアタッチ、「isTrigger」にチェックを入れてサイズを変更しておきます。また、スクリプトもアタッチしておきます。

スクリプトの中身は下記に変更します。プレイヤーが触れたら消えるようにします。
using UnityEngine; public class Cookie : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Player")) { gameObject.SetActive(false); } } }
プレハブ化をしておきます。

プレイヤーの通り道にプレハブを並べておきます。

ゲームクリアとゲームオーバー
次にゲームクリアを仮で設置します。CreateEmptyで空オブジェクトを追加し、名前をGameManagerに変更。

下記スクリプトを作成します。アイテムを全て回収したらクリアとしています。
using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager instance { get; private set; } [SerializeField] private Transform Cookies; private void Awake() { instance = this; } public void CheckCookies() { foreach (Transform cookie in Cookies) { if (cookie.gameObject.activeSelf) { return; } } Debug.Log("CLEAR"); } public void GameOver() { Debug.Log("GAMEOVER"); } }
GameManagerにアタッチして、パラメータをセットします。

Cookieスクリプトを下記のように変更します。
using UnityEngine; public class Cookie : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Player")) { gameObject.SetActive(false); GameManager.instance.CheckCookies(); } } }
ゲームオーバーも仮で設置しておきます。敵キャラにプレイヤーがぶつかったらゲームオーバーです。EnemyスクリプトにOnCollisionEnter2Dの部分を追加しただけですが、一応すべてのコードを載せておきます。
using UnityEngine; public class Enemy : MonoBehaviour { [SerializeField] private LayerMask stageLayer; [SerializeField] private Eye eye; private Rigidbody2D rb; private float speed = 7.5f; private Vector2 _direction; private Vector2 _directionReserve; private void Start() { rb = GetComponent<Rigidbody2D>(); _direction = Vector2.left; } private void Update() { if (_directionReserve != Vector2.zero) { CheckDirection(_directionReserve); } } private void FixedUpdate() { Vector2 dist = _direction * speed * Time.fixedDeltaTime; rb.MovePosition(rb.position + dist); } private void CheckDirection(Vector2 direction) { RaycastHit2D hit = Physics2D.BoxCast (transform.position, Vector2.one * 0.5f, 0.0f, direction, 1.0f, stageLayer); if (hit.collider == null) { _direction = direction; eye.ChangeEye(_direction); _directionReserve = Vector2.zero; } } private void OnTriggerEnter2D(Collider2D other) { Point point = other.GetComponent<Point>(); if (point != null) { int index = Random.Range(0, point.Directions.Count); _directionReserve = point.Directions[index]; } } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Player")) { other.gameObject.SetActive(false); GameManager.instance.GameOver(); } } }
Playerスクリプトで判断しても問題ないです。
見た目の調整
最後に少し見た目を調整します。今まではテストがしやすいように大きいサイズで進めていたので、MainCameraのサイズを15~18程度に変更。背景を黒にします。

実行してみて下記のような感じになればOK。

実際には、敵キャラがプレイヤーを追いかける動きをしたり、アイテム取得でポイントが増えたり、複数ステージやスクリプトの整理など多くのことを付け足していく感じですね。
とりあえずそれっぽいのが出来た感じです。