Having trouble with doing check if part is within another part's bounds

Hello, I’m currently stuck with figuring out how to make my game perform a check correctly. The Plot has a Plot.Base part inside of it, and I want the Object to be within the X and Z bounds of the Plot.Base part.
Currently, the code always has false positives and says the part is outside of the bounds. I’m not really good with math at all, so I don’t know how to make this happen correctly. I can’t find anything similar to my problem which is good for this use case.

Example of what I want to happen:

Code sample (Check if Property == "ScalePart" then):

local function EditObjectProperty(Player, Object, Property, NewPropertyContent)
	local Plot = GetPlotFromPlayer(Player)
	if not Plot then
		warn("This player has no plot")
		return
	end
	if Object == nil then
		warn("The specified object is nil")
		return
	end
	if Object.Parent ~= Plot then
		warn("This object is not part of their plot")
		return
	end
	if Property == nil or type(Property) ~= "string" then
		warn("Invalid property")
		return
	end

	-- Other property handlers here

	elseif Property == "ScalePart" then
		local RequestedSize = NewPropertyContent.Scale
		local RequestedPosition = NewPropertyContent.Position

		local OriginalSize = Object.Size
		local OriginalPosition = Object.Position

		Object.Size = RequestedSize
		Object.Position = RequestedPosition

		-- Check if the part exceeds the plot bounds in any direction
		local halfSizeX = Object.Size.X / 2
		local halfSizeZ = Object.Size.Z / 2
		local basePosX = Plot.Base.Position.X
		local basePosZ = Plot.Base.Position.Z
		local baseSizeX = Plot.Base.Size.X / 2
		local baseSizeZ = Plot.Base.Size.Z / 2
		local partPosX = Object.Position.X
		local partPosZ = Object.Position.Z

		if partPosX - halfSizeX < basePosX - baseSizeX or partPosX + halfSizeX > basePosX + baseSizeX or
			partPosZ - halfSizeZ < basePosZ - baseSizeZ or partPosZ + halfSizeZ > basePosZ + baseSizeZ then
			warn("Scaled part exceeds plot bounds. Scaling operation cancelled.")
			Object.Size = OriginalSize
			Object.Position = OriginalPosition
			return
		end

		Object.Size = RequestedSize
		Object.Position = RequestedPosition

	else
		warn("Invalid property")
	end
end

Any help with my problem would be much appreciated!

1 Like

I figured it out myself using this function.

local function checkIfPartIsInBounds(part, base)
	local partPos = part.Position
	local partSize = part.Size
	local basePos = base.Position
	local baseSize = base.Size

	local minX = basePos.X - baseSize.X/2
	local maxX = basePos.X + baseSize.X/2
	local minZ = basePos.Z - baseSize.Z/2
	local maxZ = basePos.Z + baseSize.Z/2

	if partPos.X - partSize.X/2 >= minX and partPos.X + partSize.X/2 <= maxX and
		partPos.Z - partSize.Z/2 >= minZ and partPos.Z + partSize.Z/2 <= maxZ then
		return true
	else
		return false
	end
end
1 Like

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