Skip to content

Instantly share code, notes, and snippets.

@Domiii
Last active October 7, 2021 17:22
Show Gist options
  • Save Domiii/2e324291f250f5b878ceaf9b91969219 to your computer and use it in GitHub Desktop.
Save Domiii/2e324291f250f5b878ceaf9b91969219 to your computer and use it in GitHub Desktop.
[Unity v5.3] Simple elevator
/**
* A simple elevator script. Can be attached to any object to make it move in the given direction.
* Requires a button that calls CallElevator().
*/
using UnityEngine;
using System.Collections;
public class Elevator : MonoBehaviour {
/// <summary>
/// The distance between two floors
/// </summary>
public Vector3 FloorDistance = Vector3.up;
public float Speed = 1.0f;
public int Floor = 0;
public int MaxFloor = 1;
public Transform moveTransform;
private float tTotal;
private bool isMoving;
private float moveDirection;
// Use this for initialization
void Start () {
moveTransform = moveTransform ?? transform;
}
// Update is called once per frame
void Update () {
if (isMoving) {
// elevator is moving
MoveElevator();
}
}
void MoveElevator() {
var v = moveDirection * FloorDistance.normalized * Speed;
var t = Time.deltaTime;
var tMax = FloorDistance.magnitude / Speed;
t = Mathf.Min (t, tMax - tTotal);
moveTransform.Translate(v * t);
tTotal += t;
print (tTotal);
if (tTotal >= tMax) {
// we arrived on floor
isMoving = false;
tTotal = 0;
Floor += (int)moveDirection;
print (string.Format("elevator arrived on floor {0}!", Floor));
}
}
/// <summary>
/// Start moving up one floor
/// </summary>
public void StartMoveUp() {
if (isMoving)
return;
isMoving = true;
moveDirection = 1;
}
/// <summary>
/// Start moving down one floor
/// </summary>
public void StartMoveDown() {
if (isMoving)
return;
isMoving = true;
moveDirection = -1;
}
/// <summary>
/// Tell the elevator to move up or down
/// </summary>
public void CallElevator() {
if (isMoving)
return;
print ("elevator starts moving!");
// start moving
if (Floor < MaxFloor) {
StartMoveUp ();
}
else {
StartMoveDown ();
}
}
}
/**
* A simple ElevatorButton, can be used to cause an Elevator start moving up or down.
*/
using UnityEngine;
using System.Collections;
public class ElevatorButton : MonoBehaviour {
public Elevator Elevator;
void OnTriggerEnter(Collider collider) {
var go = collider.gameObject;
var player = go.GetComponent<Player> ();
if (player != null && Elevator != null) {
Elevator.CallElevator ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment