【サバイバルホラーゲームを作りたい。その6】

今回もこちらの動画を参考にやっていきます。
youtu.be

今回はEキー押下によりドアがオープンするようにしていきます。

・プレイヤーがドアの前方に来たことが分かるようにBox Colliderをアタッチします。

・Eキー押下でイベントが発生するようにInput SystemのActionの設定をします。

Input System参考:
forpro.unity3d.jp

・空オブジェクトに下記スクリプトをアタッチします。

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

public class InputScript : MonoBehaviour //EP6追加 InputObjectにアタッチ
{
    InputActions inputActions;

    bool interactionInput; //EP16追加 PlayerのInteractアクションのtrue/falseを代入

    private void Awake()
    {
        if (inputActions == null)
        {
            inputActions = new InputActions();

            //Interactアクションの指定ボタンが押下された場合、InteractionInput = trueにする
            inputActions.Player.Interact.performed += i => interactionInput = true;

            //Interactアクションの指定ボタンを離した場合、InteractionInput = falseにする
            inputActions.Player.Interact.canceled += i => interactionInput = false;
        }

        //actionの追加
        inputActions.Enable();
    }

    public bool getInputActions()
    {
        return interactionInput;
    }
}

・ドア直下の空オブジェクトにスクリプトをアタッチします。

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

public class DoorOpen : MonoBehaviour //EP6追加 ドアにアタッチ
{
    public GameObject actionKey;
    public GameObject actionText;
    public InputScript inputScript;
    AudioSource audioSource;

    BoxCollider boxCollider;
    public Animator animator;

    private void Start()
    {
        boxCollider=GetComponent<BoxCollider>();
        audioSource = GetComponent<AudioSource>();
    }

    private void OnTriggerEnter(Collider other)
    {

        //コライダーにプレイヤーが当たった場合
        if (other.tag == "Player")
        {
            // Debug.Log("hit");

            //キー押下~のメッセージを表示
            actionKey.SetActive(true);
            actionText.SetActive(true);
        }
    }

    private void OnTriggerStay(Collider other)
    {
        if (other.tag=="Player")
        {
            //ドアオープン
            if (inputScript.getInputActions())
            {
                actionKey.SetActive(false);
                actionText.SetActive(false);

                boxCollider.enabled = false;
                animator.Play("FirstDoorOpenAnim");

                //ドアが開く音
                audioSource.Play();

            }
        }
    }

    ////コライダーからプレイヤーが離れた場合
    private void OnTriggerExit(Collider other)
    {
        actionKey.SetActive(false);
        actionText.SetActive(false);
    }
}

ドアの開く音は魔王魂で入手しました。
maou.audio


プレイ動画です。
youtu.be


今回は以上です。