I’m working on a system where you can pick up a brick, and then place it somewhere else. Everything works fine, except for sometimes the brick clips into walls when selected. Can anybody tell me how to fix this?
local function updateBrickPosition()
local hitPosition = mouse.Hit.Position
local hitNormal = Vector3.new(0, 1, 0)
local target = mouse.Target
if target and target:IsA("BasePart") then
hitNormal = target.CFrame:pointToWorldSpace(target.Position) - hitPosition
hitNormal = hitNormal.Unit
end
-- Calculate the adjusted position to prevent going into walls
local hitAdjustment = hitNormal * (brik.Size.Y / 2)
local adjustedPosition = hitPosition - hitAdjustment
-- Calculate the final position using grid snapping
local BlockPos = Vector3.new(0, brik.Size.Y / 2, 0) + adjustedPosition
local XPos = math.round(BlockPos.X / step) * step
local YPos = math.round(BlockPos.Y / step) * step
local ZPos = math.round(BlockPos.Z / step) * step
BlockPos = Vector3.new(XPos, YPos, ZPos)
brik.CFrame = CFrame.new(BlockPos)
brik.Transparency = 0.5
end
Use Cast Rays: Instead of calculating the hit position and normal manually, consider using Roblox’s built-in ray-casting functions like Workspace:FindPartOnRayWithIgnoreList to detect collisions. This can help you avoid issues with bricks clipping into walls.
Collision Filtering: Ensure that you are filtering out the brick itself from the ray-casting process so that it doesn’t detect collisions with itself. You can create an IgnoreList and add the brick to it.
Here’s the script of how you can update your code to use ray-casting:
-- Assuming 'mouse' and 'brik' are already defined
local function updateBrickPosition()
local ray = Ray.new(mouse.Origin, mouse.Direction * 100) -- Adjust the length as needed
local ignoreList = {brik} -- Create an IgnoreList and add the brick
local hit, hitPosition, hitNormal = workspace:FindPartOnRayWithIgnoreList(ray, ignoreList)
if hit then
-- Calculate the final position using grid snapping
local BlockPos = hitPosition - hitNormal * (brik.Size.Y / 2)
local XPos = math.round(BlockPos.X / step) * step
local YPos = math.round(BlockPos.Y / step) * step
local ZPos = math.round(BlockPos.Z / step) * step
BlockPos = Vector3.new(XPos, YPos, ZPos)
brik.CFrame = CFrame.new(BlockPos)
brik.Transparency = 0.5
end
end
This code uses a ray to find the collision point and normal with the Workspace:FindPartOnRayWithIgnoreList function. It also filters out the brick itself to prevent self-collision issues. You can adjust the ray’s length based on your needs to prevent clipping into walls.
That didn’t work, also I’ve already tried fixing the issue with ai generated responses, so please don’t use those here, 99% of the time they don’t work as intended.