Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class DrawerController : MonoBehaviour
- {
- public GameObject drawer;
- public float distance;
- public float lerpTime;
- private bool isOpen;
- private bool canInteract;
- private Vector3 startPos;
- private Vector3 endPos;
- private float currentLerpTime = 0;
- void Start()
- {
- //audio = GetComponent<AudioSource>();
- // Start position will be updated
- startPos = drawer.transform.position;
- // End position will be updated
- endPos = drawer.transform.position + Vector3.right * distance;
- }
- void Update()
- {
- //If we can interact and we press the E key, flip the isOpen bool
- if (canInteract)
- {
- if (Input.GetKeyDown(KeyCode.E))
- {
- InteractWithDrawer();
- }
- }
- //The drawer is in its proper position:
- //if it's open and it's at the end position OR if it's closed and at the start position
- bool isInPosition = (isOpen && window.transform.position == endPos) || (!isOpen && window.transform.position == startPos);
- //If the drawer is not in position, move it!
- if (!isInPosition)
- {
- //If it's meant to be open increase the currentLerpTime
- //Else decrease the currentLerpTime
- if (isOpen)
- {
- currentLerpTime += Time.deltaTime;
- }
- else currentLerpTime -= Time.deltaTime;
- //Clamp the lerp time between 0 and 1, this means it cannot go below 0 or above 1.
- currentLerpTime = Mathf.Clamp01(currentLerpTime);
- float move = currentLerpTime / lerpTime;
- window.transform.position = Vector3.Lerp(startPos, endPos, move);
- }
- }
- void OnTriggerEnter(Collider other)
- {
- if (other.gameObject.tag == "Player")
- {
- canInteract = true;
- }
- }
- void OnTriggerExit(Collider other)
- {
- if (other.gameObject.tag == "Player")
- {
- canInteract = false;
- }
- }
- //If isOpen is true set it to false, if isOpen is false set it to true
- public void InteractWithDrawer()
- {
- isOpen = !isOpen;
- Debug.Log(isOpen);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement