Daily progress: Elevator challenge
This challenge was pretty straightforward, have an elevator go through each floor and wait 5 seconds before moving on to the next, but it did present an unexpected challenge!
First, I duplicated the floorlift twice and placed them at the spots I wanted it to stop and called it WayPoint1 and Waypoint2, I then deleted everything but their transforms for their positional data. This is the exact same process as what I did in the Moving Platforms article.
While I could have just made two separate variables for each waypoint, I wanted to modularize the script a little in case there were areas with more floors, so I went with a list:
This provided a place in my Floorlift script I could drag my waypoints into, and if more floors were needed, then we could drag more in later.
As you can see, I also created a floor speed and a time to wait variable since the challenge stated it would need the elevator to stop for 5 seconds on each floor.
Since we were dealing with a list, I figured I’d use a counter to cycle through it.
So first I had the elevator moving with a Vector3.MoveTowards:
this moved the elevator down to the correct spot, so mission accomplished. then came putting in the check to see if the elevator made it to its destination. Then check for the counter. If it was at the end of the List, then reset to 0, and if not, add 1. Since MoveTowards was in the Update, we could be assured of the platforms constant movement.
Well, cool! We’re making progress!
Since we’ll need to stop at each floor, it makes sense to create a coroutine for it.
Logical right? Let’s see if it works.
It looks like it’s working when it reaches the first waypoint but then…The elevator goes nuts! What’s happening?
If you think about it, once the elevator reaches the waypoint, the transform position is going to equal that position for at least 60 frames in one second, in that time, the check will be true 60 times and the counter will continue to be modified and the elevator constantly switching directions. We need a way to make sure once the check is done, it’ s done once.
We can use a boolean that I’ll call _canCheckFloors. It will be true at the start, once the floor reaches the waypoint, it will be set to false, and once it’s out of the danger-zone of like 1 second, we’ll set it to true again so it won’t miss the next waypoint.
So _canCheckFloors is created and initially set to true. In Update, once the lifts position is equal to the waypoint, we’ll enter the coroutine and immediately make _canCheck false guaranteeing the lift will smoothly leave the area and after a second, _canCheckFloors is set back to true, assuring us that when the lift reaches the next waypoint, it will be checked again.
And everything works perfectly! On to the next challenge!