How to clamp an object to a plot?

Hello everyone,

I am making a placement system and when I try to clamp an object to the plot, the object doesn’t get clamped. Code:

function clacBounds(plot, position)
    local lPos = plot.CFrame:pointToObjectSpace(position)
    local min_x = -(plot.Size.X/2)
    local min_z = -(plot.Size.Z/2)
    local max_x = (plot.Size.X/2)
    local max_z = (plot.Size.Z/2)

    local x = math.clamp(lPos.X, min_x, max_x)
    local z = math.clamp(lPos.Z, min_z, max_z)
    local vector = Vector3.new(x, position.Y, z)

    print(vector)
    return vector
end

Video:

Thanks for the help!

What do you mean by “the object doesn’t get clamped”? That it just doesn’t respect the bounds set?

What is the purpose of the line “lPos = plot.CFrame:pointToObjectSpace(position)”?

the line gets the position relative to the plot; give me a sec while I try to upload a video; hopefully you can see the problem

1 Like

It looks like it’s clamping around the origin. When declaring the min and max positions try adding the position of the plot.

min_x = plot.Position.x - plot.Size.x / 2
max_x = plot.Position.x + plot.Size.x / 2

Try that out and see what the result is. Same with Z values.

It works, thank you, I have been looking for this answer!

1 Like