プレイヤーが特定のエリアにいるか判定する方法

投稿者: | 2019-11-04


プレイヤーがいるエリアによって床の色を変えてみます。

床のPlaneと、スタンダードアセットのFPSコントローラと、エリア判定に使うEmptyオブジェクトを配置します。

EmptyにAdd ComponentからBox Colliderをつけます。

EmptyのBox Colliderコンポーネントで、Is Triggerにチェックをいれ、Edit Colliderをクリックします。

Edit Colliderをクリックすると、オブジェクトのサイズを変えるのと同じように、コライダーのサイズを変えられます。判定したいエリアの大きさに合わせて変更します。

終わったら再度Edit Colliderをクリックします。

Emptyに新しいスクリプトをつけます。

そしてスクリプトに、OnTriggerを使って、エリアに入ったときと出たときの処理を書きます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class newScript : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            // プレイヤーがEmptyのコライダーに入ったとき
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
        {
            // プレイヤーがEmptyのコライダーから出たとき
        }
    }
}

エリアに入ったのがプレイヤーであることを知らせるために、プレイヤーに「Player」タグをつけます。このタグはデフォルトで用意されています。

床の色を変える

プレイヤーがエリアに入ったときに床の色を変えます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class newScript : MonoBehaviour
{

    public GameObject plane;
    Renderer planeRenderer;

    public Color planeColor;

    // Start is called before the first frame update
    void Start()
    {
        planeRenderer = plane.GetComponent<Renderer>();
        planeRenderer.material.color = Color.white;
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            planeRenderer.material.color = planeColor;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player")
        {
            planeRenderer.material.color = Color.white;
        }
    }

}

Rendererコンポーネントからマテリアルの色を変えています。

GetComponent<Renderer>().material.color = Color.red;

として、変える色を指定することもできますが、同じスクリプトを使いながらエリアを複数作って、それぞれに違う色を設定したい場合には、色をインスペクタから指定したほうが便利かもしれません。

public Color planeColor;

と書くとインスペクタにカラーピッカーが表示されて、ここで色を選べます。

EmptyをCtrl + Dでコピーして別の場所に配置します。

各Emptyのインスペクタから別々の色を設定できます。

コメントを残す

メールアドレスが公開されることはありません。