Please help me create a sliding door animation in Unity. I’m a beginner in this field and don’t have a good understanding of how to do it. Please.
Hello, can you help me create an animation for a door? I want to make it so that the door can be opened by pressing the “E” key on the keyboard when you are inside the button colliders and looking at them. In other words, the player should only be able to press “E” if they are inside the button colliders and looking at them at that moment. After pressing, the “DoorController” script checks the state of the door (initially, they are closed, but for some reason, the animator plays the opening animations, as shown in the video). If the door is open, it plays the closing animation (I have two of them, “DoorClose1” and “DoorClose2,” and two opening animations, “DoorOpen1” and “DoorOpen2”), and it plays the sound that I will specify later in the inspector. The animation should play only once, meaning that when the door transitions from the open state to the closed state through the animation, the animation is played once and remains in the position indicated in the last frame of the animation. Also, how can I add a delay between button presses? Let’s say, introduce a 2-3 second delay before allowing another button press.
Video:
Code:
using UnityEngine;
public class DoorController : MonoBehaviour
{
public GameObject player; // Объект игрока
public Animator doorAnimator1; // Аниматор первой двери
public Animator doorAnimator2; // Аниматор второй двери
public KeyCode interactKey = KeyCode.E; // Клавиша для взаимодействия с дверью
private bool isOpen = false; // Состояние дверей
private bool isPlayerNearButton = false; // Находится ли игрок около кнопки
private void Update()
{
if (isPlayerNearButton && Input.GetKeyDown(interactKey))
{
if (isOpen)
{
CloseDoors();
}
else
{
OpenDoors();
}
}
}
private void OpenDoors()
{
doorAnimator1.SetBool("isOpen", true);
doorAnimator2.SetBool("isOpen", true);
isOpen = true;
}
private void CloseDoors()
{
doorAnimator1.SetBool("isOpen", false);
doorAnimator2.SetBool("isOpen", false);
isOpen = false;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
isPlayerNearButton = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject == player)
{
isPlayerNearButton = false;
}
}
}