Creating an Elevator (part 3)
Calling the Elevator down & Making it go back up once the player is onboard
It is finally time to activate the elevator and make it come down to us. Similar to how we did our moving platforms, the elevator is logically speaking, is just another moving platform.
The sudo logic behind the activation and moving of the elevator is broken down into several parts. The elevator has to check whenever the player has activated the button to call down the elevator, then it also needs to know the current position of the elevator itself, then it needs to know the target location so it can travel there. Finally the elevator needs to know when the player is onboard so it can trigger the process of going back up again.
We begin by creating a new behavior script for the elevator and attach it to the game object. Very similar to the moving platform that we did before, we will need to create two transform targets which the elevator can keep track of. Then we need to create an speed variable along with a Boolean which keeps toggles the true of false mechanism.
Then we need to create a public method which the elevator panel script can access. This public method is going to contain the current transform position (which is going to be set Target A) and also the trigged Boolean (to which we set to true)
Just like how we solved for the jittery movement with the moving platform, we will again used a “Fixed Update” method instead of the standard one. In the Fixed Update we will create the set of conditions via IF statements that checks the Boolean’s state.
If the Boolean is set to true, the elevator will move towards Target B. Else if the Boolean is set to false, the position to stay/or move toward Target A.
Finally to complete this script, we need to add in the On Enter Trigger method too detect the player. The detection is set to do two things, 1) set the player object as a child object to the elevator. 2) set the Boolean status back to false so the elevator can return back to the top.
Add an On Trigger Exit and unpair the player from the elevator parent object.
Trigger the Behavior:
Back in the Elevator Panel script, we are going to give a new handle and reference to the Elevator Behavior script. Then in the If statement that controls the Input and coin conditions we will also add in the public method from the Elevator script which is “Call Elevator”.
Back in Unity, we just need to create the two empty game object which will act as Targets for the elevator. And also create an Box Collider at the elevator itself and set it to “is Trigger.” That way, when the player enters the trigger point, the Elevator will rise to the up automatically.
Now the elevator should come down when the player meets all the set conditions.