I’m making a ping pong game and I’m attempting to use a part to determine where the ball will bounce to but I want the part’s position to depend on where the character of the incoming ball is and without the part leaving the table’s surface.
(ex: character is close to the table, part goes towards the table)
You can calculate a fixed position relative to the player character in the direction of the table, then restrict that position to the table area with math.clamp.
That’s how I would do it.
-- LocalScript
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local tableSurface = workspace:WaitForChild("TableSurface")
local targetPart = workspace:WaitForChild("TargetPart")
local FORWARD_OFFSET = 4
tableSurface.Anchored = true
targetPart.Anchored = true
local function updateTargetPosition(character)
if not character or not character:FindFirstChild("HumanoidRootPart") then
return
end
local rootPart = character.HumanoidRootPart
local desiredWorldPosition = rootPart.Position + (tableSurface.CFrame.LookVector * FORWARD_OFFSET)
local tableCFrame = tableSurface.CFrame
local tableSize = tableSurface.Size
local desiredPosInTableSpace = tableCFrame:PointToObjectSpace(desiredWorldPosition)
local halfSize = tableSize / 2
local clampedX = math.clamp(desiredPosInTableSpace.X, -halfSize.X, halfSize.X)
local clampedZ = math.clamp(desiredPosInTableSpace.Z, -halfSize.Z, halfSize.Z)
local clampedY = halfSize.Y + (targetPart.Size.Y / 2)
local finalCFrameInTableSpace = CFrame.new(clampedX, clampedY, clampedZ)
local finalWorldCFrame = tableCFrame:ToWorldSpace(finalCFrameInTableSpace)
targetPart.CFrame = finalWorldCFrame
end
RunService.RenderStepped:Connect(function()
updateTargetPosition(Players.LocalPlayer.Character)
end)