Skip to content

Instantly share code, notes, and snippets.

@progrium
Created December 29, 2017 19:32
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save progrium/824849a0edd0beb206956d00da744f0f to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElevatorDoors : MonoBehaviour {
public GameObject doorLeft;
public GameObject doorRight;
public float speed = 20f;
public GameObject elevator;
public bool open = false;
private bool moving = false;
private float startTime = 0f;
private Vector3 openPosition = new Vector3(32, 0, 0);
private Vector3 closedPosition = new Vector3(16, 0, 0);
private Vector3 startPosition;
private Vector3 targetPosition;
private Vector3 nextPosition = Vector3.zero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (moving) {
var progress = ((Time.time - startTime) * speed) / Vector3.Distance (startPosition, targetPosition);
doorLeft.transform.localPosition = Vector3.Lerp (startPosition, targetPosition, progress);
doorRight.transform.localPosition = Vector3.Lerp (startPosition.WithX(startPosition.x * -1), targetPosition.WithX(targetPosition.x*-1), progress);
if (progress > 1f) {
moving = false;
if (nextPosition != Vector3.zero) {
TransitionTo (nextPosition);
nextPosition = Vector3.zero;
} else {
if (targetPosition == closedPosition && elevator != null) {
elevator.SendMessage ("Ready");
}
}
}
}
}
public void TransitionTo(Vector3 target) {
if (target == doorLeft.transform.localPosition) {
return;
}
if (!moving) {
GetComponent<AudioSource> ().Play ();
startTime = Time.time;
startPosition = doorLeft.transform.localPosition;
targetPosition = target;
moving = true;
} else {
nextPosition = target;
}
}
void OnTriggerEnter(Collider other) {
if (other.gameObject != Camera.main.gameObject) {
return;
}
Open ();
}
void OnTriggerExit(Collider other) {
if (other.gameObject != Camera.main.gameObject) {
return;
}
Close ();
}
public void Open() {
TransitionTo (openPosition);
}
public void Close() {
TransitionTo (closedPosition);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment