Creating Platforms that can move at a certain position
Adding moving platforms to our level design is one way of making the environment more interactive. It also adds in an unique gameplay dynamic which can enhance player feedback.
Setting Up the Platform:
First select the platform which will be the designated moving object. Then create an new C# script and attach the script the game object. Select the moving platform and duplicate it twice, and name the first object “Target A” and the second duplicated object “Target B”. Drag target B to an desired location which the moving platform will travel to.
tip: Since Target A and Target B are just transform targets, we can remove all components within the inspector.
Scripting the Movement:
We first need to assign several variables, the speed which the platform is moving at, the transform targets and finally an private Boolean which will track whenever the platform as reached its destination so it begin its journey to the next target. By default we need to set the Boolean to false, when it reaches its target, we can switch it back up to true.
Next in the Update method, we will need to create something called a Boolean switch. A Boolean switch basically is a true and false statement that sets up an condition for each state. In our case if the Boolean is false we set the condition to move towards target B. Then we set the Boolean status to true. Once the Boolean is state is set to true, we set the condition to travel back to target A.
To move the actual platform, there is a scripted called “Move towards”. By using this script, we take our current position and deliver an new Vector3 target along with the set speed.
Back in Unity we drag and drop both Targets into the slots and we should see that the platform now ping pongs back and forth between these two targets. Although this method is not in best practice since everything now has to be hardwired and isn’t has modular enough to be applied other uses. We are also unable to expand the target size, since it would error out if one platform object has only 2 targets when the script is asking for 3. But overall, this simple script has completed what we need for now, which is to create movement between two targets.