I want to make an automatic sliding door in Unity. The idea is, there will be a door with a sensor area. If a player inside that sensor area, the door will open, and if the player left, the door closes.
To make this thing happened in Unity, I need to make a sensor script attached to a sensor object of that door. The object is simply a cube with a collider as it trigger and it has rigidbody to make the triggering works.
Here I wrote this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AutomaticDoor : MonoBehaviour
{
public GameObject movingDoor;
public float maximumOpening = 10f;
public float maximumClosing = 0f;
public float movementSpeed = 5f;
bool playerIsHere;
// Start is called before the first frame update
void Start()
{
playerIsHere = false;
}
// Update is called once per frame
void Update()
{
if(playerIsHere){
if(movingDoor.transform.position.x < maximumOpening){
movingDoor.transform.Translate(movementSpeed * Time.deltaTime, 0f, 0f);
}
}else{
if(movingDoor.transform.position.x > maximumClosing){
movingDoor.transform.Translate(-movementSpeed * Time.deltaTime, 0f, 0f);
}
}
}
private void OnTriggerEnter(Collider col){
if(col.gameObject.tag == "Player"){
playerIsHere = true;
}
}
private void OnTriggerExit(Collider col){
if(col.gameObject.tag == "Player"){
playerIsHere = false;
}
}
}
You can watch how I did it in this video: