Nerd For Tech
Published in

Nerd For Tech

Creating a Player-Controlled Elevator

Objective: Create an elevator system the player can control with the up and down arrows.

Going down…then up.

Much like our moving platform (https://medium.com/nerd-for-tech/creating-a-moving-platform-ac53487f9498), the floors where we want our elevator to stop will be empty GameObjects with just a Transform component. However, unlike our moving platform which just has two points, we’ll store our floors in an array so we can have as many as we want.

In our elevator’s Update function, if the player is on the elevator’s floor AND the elevator does NOT has a current target, the elevator will check for the player’s input.

Before we continue, I should mention that in the set-up below, the highest floor is Element 0 and each floor beneath that increases by one. You can certainly flip this system if that works better for your own mind. The player won’t see any of this — the arrows will simply work.

If the player pressed the up arrow AND the elevator is on a floor other than the highest one, we’ll decrease the current floor count and start the MoveOverSeconds coroutine.

If the player pressed the down arrow AND the elevator is on a floor other than the lowest one, we’ll increase the current floor count and start the MoveOverSeconds coroutine.

The MoveOverSeconds coroutine needs to know our end position (the position of the new current floor) and the time it should take for the elevator to change floors.

When the coroutine starts, it flags _hasTarget to true to stop the player from giving the elevator a new command while it is moving. It then beings a timer and notes the starting position (where it currently is).

While the elapsedTime is less than the amount of time it should take the elevator to complete its move, it will calculate how far it should move each frame by using linear interpolation (Lerp). It will then update the timer and wait for the end of the current frame.

Once the time is expired, the elevator makes sure is it exactly at it ending position and sets _hasTarget to false. Now the player can one select a new floor if desired.

One final note: Just like the moving platform, we’ll need to make the player object a child of the elevator while it is riding the elevator.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store