Need help with CFrame calculation

Hello, I just ran into a problem while trying to make a part stop when it “collides” (it does not collide because its anchored) with another part.

So I am making a game where you catch balls falling from the above with a pad. The pad is anchored and controlled using CFrame. I need to make the pad stop whenever it reaches any of the borders
(see image below)

If the borders are fixed I’d just use scripted borders instead of physical borders by clamping the CFrame of the pad.

For this example I’m assuming the pad is moved by the mouse, but you can suit it to your desired control scheme later:

local PlayerService = game:GetService("Players")
local RunService = game:GetService("RunService")

local Mouse = PlayerService.LocalPlayer:GetMouse()

local Pad = workspace.Pad

-- Center of the playing area. The example assumes that the board area is in the middle of the map.
local ORIGIN = Vector3.new(0, 0, 0) 

-- Length from the origin to the edge. This is a 24x24 example.
local X_RADIUS = 12
local Z_RADIUS = 12
-- The Y plane of the pad.
local Y_HEIGHT = 2

local PAD_X = Pad.Size.X / 2
local PAD_Z = Pad.Size.Z / 2

RunService.RenderStepped:Connect(function()
	local X = X_RADIUS - PAD_X
	local Z = Z_RADIUS - PAD_Z
	
	-- Offset with the origin in case the playing area isn't in the middle of the map.
	local MousePosition = Mouse.Hit.Position - ORIGIN
	Pad.CFrame = CFrame.new(math.clamp(MousePosition.X, -X, X), Y_HEIGHT, math.clamp(MousePosition.Z, -Z, Z)) + ORIGIN
end)

1 Like

I have already solved the problem using math.min and math.max but I’m pretty sure this would have worked by looking at it so thank you for helping me! I really appreciate that you were able to explain it instead of just sending me the code without me knowing what to do with it. :smiley: