Skip to content

Instantly share code, notes, and snippets.

@pr00thmatic
Created November 27, 2021 13:11
Show Gist options
  • Save pr00thmatic/670d0dedc6118f880eaafc43dd841710 to your computer and use it in GitHub Desktop.
Save pr00thmatic/670d0dedc6118f880eaafc43dd841710 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Interact : MonoBehaviour {
[Header("Configuration")]
public string nameOfInteractable = "LUDOTECA";
public KeyCode keyToInteract = KeyCode.Space;
public KeyCode keyToExit = KeyCode.Escape;
[Header("Information")]
public bool isInteracting;
public bool isInTrigger = false;
public Player player;
[Header("Initialization")]
public Text interactText;
public Transform playerSnap;
public Camera specialCamera;
public Collider myCollider;
void Update () {
if (isInteracting) {
AllowExitInteraction();
}
if (isInTrigger) {
CheckInteraction();
}
}
void OnTriggerStay (Collider c) {
Player player = c.GetComponentInParent<Player>();
if (!player) return;
this.player = player;
if (!isInteracting) {
isInTrigger = true;
interactText.text = "Presione " + keyToInteract + " para usar la " + nameOfInteractable;
CheckInteraction();
} else {
AllowExitInteraction();
}
}
void OnTriggerExit (Collider c) {
isInTrigger = false;
interactText.text = "";
}
public void AllowExitInteraction () {
interactText.text = "Presione " + keyToExit + " para usar la " + nameOfInteractable;
if (Input.GetKeyDown(keyToExit)) {
if (myCollider) myCollider.enabled = true;
isInTrigger = false;
if (specialCamera) specialCamera.gameObject.SetActive(false);
interactText.text = "";
isInteracting = false;
}
}
public void CheckInteraction () {
if (Input.GetKeyDown(keyToInteract)) {
if (myCollider) myCollider.enabled = false;
player.transform.position = playerSnap.position;
player.transform.rotation = playerSnap.rotation;
if(specialCamera) specialCamera.gameObject.SetActive(true);
isInteracting = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment