You can utilize the math function min
and max
here. These functions will return to you either the maximum or minimum of the variant number of arguments given to it.
But we don't want the minimum value or the maximum value, we want a value "clamped" between the two. With a little logic, we get this:
1 | local function clamp(n, low, high) |
2 | return math.min(math.max(n, low), high) |
However, if the high and low values are supplied the wrong way, this would give the wrong answer. You can do a little check to fix this issue, however it is not necessary if it is used correctly.
1 | local function clamp(n, a, b) |
3 | a, b = math.min(a, b), math.max(temp, b) |
4 | return math.min(math.max(n, a), b) |
You can use this function to return to you your x and z coordinates clamped between the bounds you want.
Usage Example:
02 | local highBounds = Vector 3. new( 100 , 0 , 100 ) |
03 | local lowBounds = Vector 3. new(- 100 , 0 , - 100 ) |
05 | local part = game.Workspace.Part |
07 | local x = clamp(part.Position.X, lowBounds.X, highBounds.X) |
08 | local y = clamp(part.Position.Y, lowBounds.Y, highBounds.Y) |
09 | local z = clamp(part.Position.Z, lowBounds.Z, highBounds.Z) |
10 | part.Position = Vector 3. new(x, y, z) |
So if desired Part position was Vector3.new(132, -32, -92) then the part would be positioned at Vector3.new(100, 0, -92).