Hello,
I’ve been trying to create a grid placement system where the player can place objects on a grid to create buildings.
The system mostly works, except sometimes objects can snap inside other ones!
I have been searching for a fix for a while, but I can’t seem to find a good solution.
My current raycast code:
local mouse = plr:GetMouse()
local gridsize = 1
local function mouseraycast()
local mousePosition = uis:GetMouseLocation()
local mouseRay = cam:ViewportPointToRay(mousePosition.X,mousePosition.Y)
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = {cam,char}
local raycastResult = workspace:Raycast(mouseRay.Origin,mouseRay.Direction * 1000,raycastParams)
return raycastResult
end
local function RoundToNearest(number: number, roundTo: number): number -- Handy function to remember
local x = number + (roundTo / 2)
return x - (x % roundTo)
end
local placeholder
local function UpdatePlaceholder()
placeholder = game.ReplicatedStorage.buildingstuff.smallpart:Clone()
placeholder.Transparency = 0.5
placeholder.CanQuery = false
placeholder.Parent = workspace.CurrentCamera
end
event.OnClientEvent:Connect(function()
if building == false then
building = true
game:GetService("RunService").RenderStepped:Connect(function()
if not placeholder then
UpdatePlaceholder()
end
local ray = mouseraycast()
if ray and ray.Instance then
placeholder:PivotTo(CFrame.new(RoundToNearest(ray.Position.X,placeholder.Size.X),RoundToNearest(ray.Position.Y,placeholder.Size.Y),RoundToNearest(ray.Position.Z,placeholder.Size.Z)))
end
end)
end
end)
mouse.Button1Down:Connect(function()
if building and placeholder then
local new = game.ReplicatedStorage.buildingstuff:FindFirstChild(placeholder.Name):Clone()
new:PivotTo(placeholder.CFrame)
new.Parent = workspace
end
end)