Viksy

Door

Jul 16th, 2022
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Door : Interactable
  6. {
  7.     public AudioSource audioSource;
  8.     public AudioClip audioClip;
  9.  
  10.     public bool shouldAutoClose = false;
  11.     public float timeBeforeClosing;
  12.     public float distanceBeforeClosing;
  13.  
  14.     public bool isOpen = false;
  15.     public bool canBeInteractedWith = true;
  16.     public bool isForcing = false;
  17.     private Animator anim;
  18.  
  19.     private void Start()
  20.     {
  21.         anim = GetComponent<Animator>();
  22.         audioSource = GetComponent<AudioSource>();
  23.     }
  24.  
  25.     private void Update()
  26.     {
  27.         if (isForcing)
  28.         {
  29.             canBeInteractedWith = false;
  30.             isOpen = false;
  31.             anim.SetFloat("dot", 0);
  32.             anim.SetBool("isOpen", isOpen);
  33.         }
  34.     }
  35.  
  36.     public override void OnInteract()
  37.     {
  38.         if(canBeInteractedWith)
  39.         {
  40.             isOpen = !isOpen;
  41.             audioSource.PlayOneShot(audioClip);
  42.  
  43.             Vector3 playerTransformDirection = PlayerController.instance.transform.position - transform.position;
  44.             Vector3 doorTransformDirection = transform.TransformDirection(Vector3.forward);
  45.             float dot = Vector3.Dot(playerTransformDirection, doorTransformDirection);
  46.  
  47.             Debug.Log(dot);
  48.  
  49.             anim.SetFloat("dot", dot);
  50.             anim.SetBool("isOpen", isOpen);
  51.  
  52.             if(shouldAutoClose)
  53.             {
  54.                 StartCoroutine(AutoClose());
  55.             }
  56.         }
  57.     }
  58.  
  59.     public override void OnFocus()
  60.     {
  61.  
  62.     }
  63.  
  64.     public override void OnLoseFocus()
  65.     {
  66.  
  67.     }
  68.  
  69.     private void Animator_LockInteraction()
  70.     {
  71.         canBeInteractedWith = false;
  72.     }
  73.  
  74.     private void Animator_UnlockInteraction()
  75.     {
  76.         canBeInteractedWith = true;
  77.     }
  78.  
  79.     private IEnumerator AutoClose()
  80.     {
  81.         while(isOpen)
  82.         {
  83.             yield return new WaitForSeconds(timeBeforeClosing);
  84.  
  85.             if(Vector3.Distance(transform.position, PlayerController.instance.transform.position) > distanceBeforeClosing)
  86.             {
  87.                 isOpen = false;
  88.                 anim.SetFloat("dot", 0);
  89.                 anim.SetBool("isOpen", isOpen);
  90.             }
  91.         }
  92.     }
  93. }
  94.  
Add Comment
Please, Sign In to add comment