Moving Platform¶
Difficulty¶
This is a medium tutorial.
Concepts Involved¶
- Script Handles
- Luau's type solver
- The table library
- Lerping
Setup¶
You need to create a Script Handles and attach it to the Part.
You will then need to create as many slots as you need in in the Script Handles: Pos1, Pos2, ..., PosN, with N being your final number.
Code¶
- This line creates the
SPEEDvariable, in studs per second. This controls how fast the platform travels between positions. - This is the distance, in studs, at which the platform is considered to have "arrived" at its target.
- This creates a type for each stop the platform will visit: an
ordernumber (for sorting), and theposition/orientationit should move to. - This loop runs once for every handle found in the Script Handles, using their name (for
order) and position/orientation. - This splits the handle's name around the text
"Pos", so a handle namedPos1becomes{ "", "1" }. We want the second element, which is used as theorder. - The
order, orsplit[2], is a string, sotonumberconverts it to an actual number for sorting later. If it isn't a valid number, it defaults to1. table.sortreorderspositionsso the platform visits them in ascendingorder, regardless of what order the handles were found in.- These two lines cache the platform's starting position and orientation. This is the running "current" position that gets moved on each
Update. - This tracks which entry in
positionsthe platform is currently moving toward. toTargetis the vector from where the platform currently is to where it needs to go..Magnitudegives the remaining distance.stepis how far the platform should move this frame, based onSPEEDanddt. Multiplying the speed bydtensures it moves smoothly despite lag.- If the remaining distance is smaller than this frame's step (or under the threshold), moving the full
stepwould overshoot the target. - If the platform just reached the last position in the list, this wraps
currentIndexback to1, so the platform loops back to the start. - Dividing
toTargetby its owndistanceproduces a unit vector. This is needed sostepcontrols the distance moved. - The platform moves
stepstuds alongdirectionthis frame, producing linear motion instead of an eased curve.