How to clamp CFrame (make bounds)?

Hi Guys, so I’m trying to make a simple placement system but there is a simple question I want to ask, how do I clamp CFrame ? It means I want something to not go beyond the desired CFrame. How do I achieve that ? I assume it could be done using math.clamp. Thanks :smile:

When you say clamp a CFrame are you talking about clamping it relative to a plot’s size? Or just clamping it relative to world coordinates?

If the former, you’d do something like:

local function clampVector(size: Vector3, vector: Vector3)
    return Vector3.new(
        math.clamp(vector.X, -size.X / 2, size.X / 2), -- note we divide the size by 2, else it will go outside of the bounds of the plot
        vector.Y,
        math.clamp(vector.Z, -size.Z / 2, size.Z / 2)
    )
end

local plot = workspace.Plot

local mouseCFrameRelativeToPlot = plot.CFrame:ToObjectSpace(mouse.Hit)

local clampedPosition = clampVector(plot.Size, mouseCFrameRelativeToPlot.Position)
-- now just apply orientation then translate it back to world space
local finalCFrame = plot.CFrame:ToWorldSpace(CFrame.new(clampedPosition) * someOrientation)

If it’s relative to world position you can do the same but there’s no need to translate it from and to world space

1 Like

Thanks for your help ! I just wanted to ask one thing, in clampVector function, you added a size parameter, but where did you assigned the size when you called the function ? Is it plot’s size ? Also, is it necessary though to convert it back to World Space ? These are just my questions, but thanks for your help.

Yeah that’s my bad, it should be the plot’s size. I edited the function

Yeah, if you don’t translate it back to world space it’ll be at the origin with the same offset that the mouse’s hit position is relative to the plot. I don’t know if that makes sense but yeah

1 Like

So you mean if the part is 15 studs away from the plot’s centre, it would be placed 15 studs away from the world’s centre (0,0,0) ? I don’t really get this but this is assumption.

Yes, that is correct. I was sort of tripping over my words lol

1 Like

Thanks! I have one more last doubt, sorry. Why is it important to divide the size in X and Z by 2 ? I’m trying to figure out the math but couldn’t lol

EDIT- I’m one more time assuming that the max X position it can go is, say 256, so because of math.clamp, number remains between 256 and -256 so it doesn’t go outside.

If you don’t it will go past the plot’s boundary.

Since the plot’s CFrame is in the centre of the plot part, if you subtract or add by one of its axes’ full sizes, it will be able to go 2x the intended distance.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.