I’m trying to make an elevator platform that moves between floors. The basic idea is that the scrip is attached to the eleveator itself. A trigger box checked weather he player is on it.
the elevators coordinates are X = -3, Y = -21, Z = 196 at start with the other two floors being at Y = -51 and Y = -90 respectively.
I tried writing it like his, but it moves just a little and stops. Obviously my method is flawed. So suggestions are needed.
Could I simply do a update/LERP of a position along Y axis by 0.1 every update? Is there a better/more efficient way?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlatformElevator : MonoBehaviour
{
public int[] stops;
public Vector3[] coordinates; //manual input of floor coordinates
public float smoothing = 10f;
[SerializeField] private int currentFloor;
public Text elevatorText;
private bool onElevator;
private bool inTransit = false;
private Vector3 destination;
private bool directionUp; //unused
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < stops.Length; i++)
{
if (coordinates[i] == transform.position)
{
currentFloor = i;
}
}
}
// Update is called once per frame
void Update()
{
if ((Input.GetKeyDown(KeyCode.DownArrow) == true) && (onElevator == true) && inTransit == false) //if going down
{
inTransit = true; // lock further movement orders until next floor
if (currentFloor == stops.Length - 1)
{
Debug.Log("Already at bottom floor.");
}
else
{
destination = coordinates[currentFloor + 1];
transform.position = Vector3.Lerp(transform.position, destination, smoothing * Time.deltaTime);
}
}
if ((Input.GetKeyDown(KeyCode.UpArrow) == true) && (onElevator == true) && inTransit == false) //if going up
{
inTransit = true;
if (currentFloor == 0)
{
Debug.Log("Already at top floor.");
}
else
{
destination = coordinates[currentFloor - 1];
transform.position = Vector3.Lerp(transform.position, destination, smoothing * Time.deltaTime);
}
}
if(transform.position == destination)
{
inTransit = false;
for (int i = 0; i < stops.Length; i++)
{
if (coordinates[i] == destination)
{
currentFloor = i;
}
}
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
elevatorText.gameObject.SetActive(true);
onElevator = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
elevatorText.gameObject.SetActive(false);
onElevator = false;
}
}
}
Perhaps changing the bit in the key press (else) to this?
finalDestination = coordinates[currentFloor - 1];
//transform.position = Vector3.Lerp(transform.position, destination, smoothing * Time.deltaTime);
destination = new Vector3(transform.position.x, (float)(transform.position.y+0.1), transform.position.z);
transform.position = Vector3.Lerp(transform.position, destination, smoothing * Time.deltaTime);
and then check for finalDesitionaion instead of destination?
EDIT: Nope, doesn’t work at all… hmm…
