Creating Elevator in Unity — Part 3: Moving Elevator.

Objective: Move the elevator to the elevator panel position when the player calls the elevator and move it back to the origin when the player enters the elevator.

First I created an elevator script and attached it to the elevator prefab. I declared some variables, the first 2 variables pointA and pointB are the transform of the origin and target of the elevator. posA and posb are Vector3 where we are going to store the initial position of pointA and pointB. Move forward is a bool variable that we are gonna use to change the direction of the elevator and speed is the speed of the elevator.

In the same script I created 2 functions (MoveForward and MoveBackwards) to change the value of the _moveForward variable. Then in the FixedUpdate function I check the value of the _moveForward variable and use the MoveTowards to move the elevator to the point A or B depending on the case.

Continuing with this script I use the OnTriggerEnter function to check if the player entered the elevator and change the value of _moveTowards to false (it makes the player move to point B).

In the elevator panel script I created a variable to get the elevator handler and in the if statement where we check if the player pressed the “E” key we call the function MoveForward() of the elevator script and it makes the elevator move to point A.

And that’s it!!! Now the elevator works.



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
Rusben Guzman

Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.