(スクリプト)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerMovement_1 : MonoBehaviour
{
private CharacterController controller;
public float speed;
private Vector3 moveDirection = Vector3.zero;
private float gravity = 9.8f;
private int keyCount = 0;
public Text keyLabel;
// 追加
public GameObject door;
public AudioClip openSound;
public AudioClip closeSound;
void Start()
{
controller = GetComponent<CharacterController>();
keyLabel.text = "✖️" + keyCount;
}
void Update()
{
moveDirection.z = Input.GetAxis("Vertical");
transform.Rotate(0, Input.GetAxis("Horizontal") * 3.5f, 0);
if(moveDirection.magnitude > 0.1f)
{
Vector3 globalDirection = transform.TransformDirection(moveDirection);
controller.Move(globalDirection * speed * Time.deltaTime);
}
moveDirection.y -= gravity * Time.deltaTime;
if(controller.isGrounded)
{
moveDirection.y = 0;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Key"))
{
Destroy(other.gameObject);
keyCount = keyCount + 1;
keyLabel.text = "✖️" + keyCount;
}
// 追加
// ポイント(keyCountの条件追加・・・>鍵を持っていないと扉は開かない)
if(other.CompareTag("UnLock") && keyCount > 0)
{
door.SetActive(false);
AudioSource.PlayClipAtPoint(openSound, transform.position);
// ポイント
// keyCountを1減らす
keyCount -= 1;
keyLabel.text = "✖️" + keyCount;
// 2秒後に扉は閉まる。
Invoke("Close", 2f);
}
}
// 追加
void Close()
{
door.SetActive(true);
AudioSource.PlayClipAtPoint(closeSound, transform.position);
}
}
(実行結果)
- 鍵を持っていない状態で触れても扉は開かない。
- 鍵を持った状態で触れると扉が開く。
- 2秒後に扉が閉まる。