2.5D Phase 1 Framework: Elevator
No sweat, I did this before!
2.5D Phase 1 Framework Challenge
For today's challenge, I created a functional lift system with a 5-second delay before moving from point A to B. I went through an elevator system before as well as a moving platform system and they are mostly all the same under the hood.
What do I need?
I need the elevator to go from A to B. So two transforms with their unique position in world space. A float variable for the speed of the elevator. A float variable for the wait time before switching towards the other point. And lastly, a bool for switching.
In the Elevator script attached to the lift game object, I have:
[SerializeField] private Transform _pointA, _pointB;
[SerializeField] private float _speed = 3f;
[SerializeField] private float _waitTime = 5f;
private bool _switch = false;
I want the bool to control when I can switch from one point to the other. So before switching, I want there to be a 5-second delay. Using a coroutine will help me with the delay.
IEnumerator WaitBeforeSwitchingRoutine(bool _canSwitch)
yield return new WaitForSeconds(_waitTime);
_switch = _canSwitch;
After 5-seconds, switch!
In FixedUpdate, if the current position equals point A, then switch is true. Else if the current position equals point B, switch is false.
if (transform.position == _pointA.position)
else if (transform.position == _pointB.position)
If switch is false, then I want the current position to move to point A. If switch is true, then I want the current position to move to point B.
transform.position = Vector3.MoveTowards(transform.position, _pointA.position, _speed * Time.fixedDeltaTime);
transform.position = Vector3.MoveTowards(transform.position, _pointB.position, _speed * Time.fixedDeltaTime);
I now have a working elevator system that loops back and forth with a wait time delay!
When the player goes on it, the player jitters. The reason being is that the player is not parented to the elevator. To fix it, I attached a box collider set as a trigger and adjusted the y-positon of the collider so it can detect the player.
In the Elevator script, when the player collides with this trigger, I want to parent the player to the elevator transform.
private void OnTriggerEnter(Collider other)
other.transform.parent = transform;
And if the player exits the trigger, I want the parent of the player not to be in the elevator game object’s transform anymore.
private void OnTriggerExit(Collider other)
other.transform.parent = null;
Now it’s working like a charm!