I have this block of code which makes a block follow your mouse in a grid
local runservice = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local block = game.Workspace:WaitForChild("Block")
local camera = game.Workspace.CurrentCamera
local cameraPart = game.Workspace.camerapart
local gridSize = 3
local castParams = RaycastParams.new()
castParams.FilterType = Enum.RaycastFilterType.Exclude
castParams.FilterDescendantsInstances = {block, cameraPart}
local function roundToGrid(n, grid)
return math.floor((n + grid / 2) / grid) * grid
end
local function followMouse()
local mouseLocation = UserInputService:GetMouseLocation()
local unitRay = camera:ViewportPointToRay(mouseLocation.X, mouseLocation.Y)
local cast = workspace:Raycast(unitRay.Origin, unitRay.Direction * 1000, castParams)
if cast then
local x = roundToGrid(cast.Position.X, gridSize)
local z = roundToGrid(cast.Position.Z, gridSize)
block.Position = Vector3.new(x, 2.5, z)
end
end
And I have a grid pattern on the floor of my game. I want my block to follow the grid pattern. my pattern looks like this:
And as you can see my part is not following the grid pattern:
There’s nothing wrong with your grid alignment code to begin with. the problem is that those black & white tiles themselves aren’t aligned to the grid. You need to move those tiles so that they are aligned.
You could try getting the tile at the top left corner, converting the mouse position to a location relative to that tile (tile.CFrame:PointToObjectSpace(cast.Position)), align that position to the grid, and then convert it back to world space (tile.CFrame:PointToWorldSpace(alignedPosition)).
local players = game:GetService("Players")
local player = players.LocalPlayer
local mouse = player:GetMouse()
local tilesFolder = --Folder with your tiles
local tileSize = tilesFolder:FindFirstChildOfClass("Part").Position.X
local heightOffet = CFrame.new(0, (tileSize.X/ 2) + (tileSize.Y/ 2), 0)
local blockPart = Instance.new("Part")
blockPart.Anchored = true
blockPart.CanCollide = false
blockPart.Size = Vector.new(tileSize, tileSize, tileSize)
blockPart.Parent = workspace
mouse.Button1Down:Connect(function()
--
local target = mouse.Target
--
if target.Parent ~= blocksFolder then return end
--
blockPart.CFrame = target.CFrame * heightOffset
--
end
(Created on mobile, errors/ bugs could be present)