Create a Rotating Elevator in Unity using Simple Math
If you can put your fear of the dreaded ‘M’ word aside, I promise to show you some simple math that can be used in your day to day life with Unity (or any other game engine for that matter).
To start things off we can add a cube to our scene along with a “Platform” script. Within the script, let’s add two Transform fields for our top and start and end locations, a bool to determine if we have reached the end, and a speed of type float:
Back in our scene, let’s create 2 empty game objects and position them where we want them to go:
Let’s place the script on our platform and plug in the 2 positions:
With our start and end positions, we have the platform move between them with some simple logic:
This will move the platform in a ping-pong like method. We just need to rotate the platform.
You may be thinking “Why not just animate the platform, so that it make a complete revolution between the 2 locations?”. This would only work if you have a set distance / time that wouldn’t change. What if you wanted to have the same logic but with a different distance? You would need some serious tweaking to your animations.
I’m here to show you a better way. We can use 2 simple slope equations to convert the distance to a rotation:
This may look like greek but it a lot simpler than it looks.
The y variables will represent our rotation in this case and the x will represent the positions. We want to rotate from 0–360 based on our _start and _end positions. We can rewrite the formulas like this:
Let’s plug these equations into our script and adjust our local euler angles:
Now we can move the start and end positions where ever we want and we will still maintain a 0 rotation at the start and a 360 rotation at the end: