Building an Elevator — Ups and Downs
Starting with the elevator panel, I created a new c# script (ElevatorPanel).
Inside this script I created references to the player, the amount of coins the player needs to have collected to progress, the meshrenderer of the button, and the elevator itself.
_player is set to the player character, allowing this script to contact the player controller.
_requiredCoins is a check to make sure the player has collected all previous coins before progressing. This is compared to the player.cs script’s _coins variable that tracks the total coins collected.
_buttonColor allows us the change the visuals of the elevator button, letting the player know it works!
Finally, the _elevator is a reference to the elevator gameobject itself; we need this to communicate with the elevator.cs script (to be covered later in this article).
Using OnTriggerStay, we check if the player is colliding with a collider, and if they are, we check for an input and if they are carrying enough coins.
If that is true, we swap the button’s color and we call the CallElevator function from the Elevator object.
Now for the elevator itself:
This is a different c# script attached to the elevator gameobject (Elevator.cs)
We need a few variables here as well:
isGoingDown is a boolean tracking which direction the elevator is currently navigating to (up or down).
_origin and _target are two transforms (locations) we need to set to the two possible stopping locations of the elevator itself.
finally, _speed is just a float to control how fast the elevator ascends or descends.
With the variables set, we used FixedUpdate() to manage the movement of the elevator itself.
When isGoingDown is true, we move towards the _target.position location (the bottom floor).
When isGoingDown is false, we move towards the _origin.postion location (the top floor).
The logic to change the boolean is quite simple:
This function is called from the elevator panel, so now when the player interacts with the panel it will flip the bool, allowing the player to control when the elevator comes down or goes back up.
Finally, we need to add the ability for the player to make the elevator go back up when they are on it.
Finally, in order to avoid stuttering while on the elevator, we need to parent the player to the elevator while they are colliding with this collider. This is identical to how I did it in my moving platforms article, but here is the code again;
This simple elevator system can be expanded upon to an infinite number of floors, speeds, functions, and more. This modular baseline allows for a reusable concept that can be used to prototype both 2D and 3D games moving forward!