80 lines
2.3 KiB
C#
80 lines
2.3 KiB
C#
|
|
using UnityEngine;
|
||
|
|
using System.Collections;
|
||
|
|
|
||
|
|
public class GarageDoor : MonoBehaviour
|
||
|
|
{
|
||
|
|
[Header("Detection Settings")]
|
||
|
|
[Tooltip("How close the player needs to be for the door to open.")]
|
||
|
|
public float openDistance = 50f;
|
||
|
|
|
||
|
|
[Header("Movement Settings")]
|
||
|
|
[Tooltip("The physical door object that moves.")]
|
||
|
|
public Transform doorMesh;
|
||
|
|
[Tooltip("How far and in what direction the door slides when open (e.g., Y = 4.5 to slide up).")]
|
||
|
|
public Vector3 openOffset = new Vector3(0f, 4.5f, 0f);
|
||
|
|
public float moveSpeed = 3f;
|
||
|
|
|
||
|
|
private Transform player;
|
||
|
|
private Vector3 closedLocalPos;
|
||
|
|
private Vector3 openLocalPos;
|
||
|
|
|
||
|
|
private bool isOpen = false;
|
||
|
|
private bool isClosedPermanently = false;
|
||
|
|
|
||
|
|
void Start()
|
||
|
|
{
|
||
|
|
// If they didn't assign a child mesh, assume this object itself is the door
|
||
|
|
if (doorMesh == null) doorMesh = this.transform;
|
||
|
|
|
||
|
|
closedLocalPos = doorMesh.localPosition;
|
||
|
|
openLocalPos = closedLocalPos + openOffset;
|
||
|
|
|
||
|
|
// Automatically find the player
|
||
|
|
GameObject p = GameObject.FindGameObjectWithTag("Player");
|
||
|
|
if (p != null) player = p.transform;
|
||
|
|
}
|
||
|
|
|
||
|
|
void Update()
|
||
|
|
{
|
||
|
|
// Don't open again if the level has ended!
|
||
|
|
if (isClosedPermanently || player == null) return;
|
||
|
|
|
||
|
|
// Check distance to player
|
||
|
|
float distance = Vector3.Distance(transform.position, player.position);
|
||
|
|
|
||
|
|
if (distance <= openDistance && !isOpen)
|
||
|
|
{
|
||
|
|
OpenDoor();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OpenDoor()
|
||
|
|
{
|
||
|
|
isOpen = true;
|
||
|
|
StopAllCoroutines();
|
||
|
|
StartCoroutine(AnimateDoor(openLocalPos));
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Called by the SafeHouseTrigger when the player parks inside.
|
||
|
|
/// </summary>
|
||
|
|
public void CloseDoor()
|
||
|
|
{
|
||
|
|
isClosedPermanently = true; // Locks the door so it doesn't open again
|
||
|
|
StopAllCoroutines();
|
||
|
|
StartCoroutine(AnimateDoor(closedLocalPos));
|
||
|
|
}
|
||
|
|
|
||
|
|
private IEnumerator AnimateDoor(Vector3 targetLocalPos)
|
||
|
|
{
|
||
|
|
while (Vector3.Distance(doorMesh.localPosition, targetLocalPos) > 0.01f)
|
||
|
|
{
|
||
|
|
// Smoothly slide the door to the target position
|
||
|
|
doorMesh.localPosition = Vector3.Lerp(doorMesh.localPosition, targetLocalPos, Time.deltaTime * moveSpeed);
|
||
|
|
yield return null;
|
||
|
|
}
|
||
|
|
doorMesh.localPosition = targetLocalPos;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|