Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you make an object follow your mouse on a grid?

I'm trying to get a part to follow my mouse on a grid, but it just feels... off... It does not feel like I'm doing the grid part correctly. I tried using both math.ceil and math.floor;

local camera = workspace.CurrentCamera;
local mouse = game.Players.LocalPlayer:GetMouse();

local previewItem = Instance.new("Part");
previewItem.Parent = game.Workspace;
previewItem.Size = Vector3.new(1, 1, 1);

mouse.Move:Connect(function()
	local unitRay = camera:ScreenPointToRay(mouse.X, mouse.Y);
	local ray = Ray.new(unitRay.Origin, unitRay.Direction * 500);
	
	local part, pos = workspace:FindPartOnRayWithIgnoreList(ray, {game.Players.LocalPlayer.Character, previewItem});
	
	if part then
		previewItem.Position = Vector3.new(math.floor(pos.X / 5) * 5, math.floor(pos.Y / 5) * 5, math.floor(pos.Z / 5) * 5);
	end;
end);

What am I doing wrong and how should I be doing it?

It follows my mouse perfectly without the grid code, the grid code is causing the issue.

1 answer

✓ Accepted answer

I'd recommend using something like this:

function round(n)
	return math.floor(n + .5)
end

to round a value.

Your script but with the change:

local camera = workspace.CurrentCamera;
local mouse = game.Players.LocalPlayer:GetMouse();

local previewItem = Instance.new("Part");
previewItem.Parent = game.Workspace;
previewItem.Size = Vector3.new(1, 1, 1);

mouse.Move:Connect(function()
    local unitRay = camera:ScreenPointToRay(mouse.X, mouse.Y);
    local ray = Ray.new(unitRay.Origin, unitRay.Direction * 500);

    local part, pos = workspace:FindPartOnRayWithIgnoreList(ray, {game.Players.LocalPlayer.Character, previewItem});

    if part then
        previewItem.Position = Vector3.new(round(pos.X), round(pos.Y), round(pos.Z);
    end;
end);

3 comments

1

It's much better but it still doesn't quite feel right.

1

Then i'd suggest removing the division and multiplication part.

1

Thanks, it works really well now!

This discussion is preserved as it was. New answers, comments, and votes are closed.