2.5D Platformer: Setting up the Elevator, Part 3
In this article, I will have the Elevator move down to the Player when the call button is pressed.
I’ll start by creating a script named Elevator and adding it to the Elevator Gameobject.
Within the Elevator script, I create a method that will be used to call the Elevator named, intuitively enough, CallElevator(). This method will be called when the Call Button on the Elevator Panel is pressed.
I do this by creating a Serialized private variable of the type Elevator named _ Elevator.
I then drag the Elevator GameObject into the appropriate space in the Inspector for the Elevator_Panel GameObject.
Now, I can add a statement to call the CallElevator() method when the “E” key is pressed.
What’s left is to program the Elevator movement into the CallElevator() method.
I’ll first create two duplicates for the Elevator GameObject and name one SecondFloor and the other FirstFloor. Then, I’ll leave the second floor at the same location and move the FirstFloor down to the lower level. Then I’ll remove all of the components except for the Transform.
In the Elevator script, I’ll create a boolean variable named _goingDown, which defaults to false, and two Serialized Transform variables named _secondFloor and _firstFloor.
Once I save and go back into Unity, I’ll drag the GameObjects FirstFloor and SecondFloor into the correct places in the Inspector.
Now I’ll create a FixedUpdate() method and, using an if statement, check the value of _goingDown and move the Elevator appropriately using Vector3.MoveTowards(). I’ll also create a float called _speed to control how fast the elevator moves.
When pressing the Call Elevator button, the Elevator will move down as long as we have enough coins.
In the next article, I’ll set up the behavior for the Elevator to go back up when the Player presses the “E” key again.
Until then, as always, I wish you the best on your gamedev and coding journey.