今回はプレイヤーキャラのスクリプトを改造してアイテムの消去とゲームオーバー処理を追加します。
改造後のプレイヤーキャラのプログラム
スクリプトを以下のように書き換えてください。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
//インスペクタに表示する変数
[SerializeField]
float speed = 0.0f;
[SerializeField]
float jumpPower = 30.0f;
[SerializeField]
Transform groundCheck;
[SerializeField]
int itemScore = 500;
//インスペクタには表示しない変数
bool jumped = false;
bool grounded = false;
bool groundedPrev = false;
bool inCamera = false;
Animator animator;
Rigidbody2D rigidBody2D;
GameManager gameManager;
//初期化
void Start () {
//コンポーネントを取得
animator = GetComponent<Animator>();
rigidBody2D = GetComponent<Rigidbody2D>();
//GameManagerを検索し、コンポーネントを取得
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
//毎フレームの処理(一般)
void Update()
{
//接地チェック
//GroundCheckオブジェクトに床などが重なってるならtrue
grounded = (Physics2D.OverlapPoint(groundCheck.position) != null) ? true : false;
//接地してるかどうかの分岐
if (grounded)
{
//接地しているならジャンプを許可
if (Input.GetMouseButtonDown(0))
{
Jump();
}
}
//ジャンプしてるかどうかの分岐
if (jumped)
{
animator.SetTrigger("Jump");
//ジャンプ終了(前フレームで接地してなくて、今のフレームで接地したとき)
if (!groundedPrev & grounded)
{
jumped = false;
}
}
else
{
animator.SetTrigger("Dash");
}
//このフレームの接地状態を保存
groundedPrev = grounded ? true : false;
}
//毎フレームの処理(物理演算)
void FixedUpdate()
{
if (grounded)
{
rigidBody2D.velocity = new Vector2(speed, rigidBody2D.velocity.y);
}
}
//ジャンプ
void Jump()
{
jumped = true;
rigidBody2D.velocity = Vector2.up * jumpPower;
}
//死亡処理
public void Dead()
{
gameManager.GameOver();
rigidBody2D.Sleep();
Destroy(gameObject);
}
//アイテムと衝突した時の処理
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Item")
{
//スコア加算
gameManager.score += itemScore;
//取ったアイテムを消す
Destroy(other.gameObject);
}
}
//カメラ内外の判定処理
void OnBecameVisible()
{
inCamera = true;
}
void OnBecameInvisible()
{
if (inCamera)
{
Dead();
}
}
}
追加部分の説明
死亡処理
ゲームオーバー画面を呼び出し、プレイヤーキャラ自身を削除します。
アイテムと衝突したときの処理
アイテムと衝突したとき、スコアを加算してアイテムを消去します。OnCollisionEnter2Dメソッドを使うと、別のオブジェクトと衝突したときにの処理を簡単に作ることができます。ここでは衝突したオブジェクトのタグが「Item」ならスコアを加算し、衝突した相手のオブジェクトを削除する処理を行っています。
カメラ内外の処理
壁やアイテムと同様にカメラに入った時と出たときの処理です。カメラから出たら死亡処理を呼び出します。
これでゲームが十分遊べるレベルになりました!あとは仕上げを行っていきます。
次のページ→背景を作る
