Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by
Nowaha 459 Moderation Voter
4 years ago
Edited 4 years ago

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

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

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);
1
It's much better but it still doesn't quite feel right. Nowaha 459 — 4y
1
Then i'd suggest removing the division and multiplication part. Vinceberget 1420 — 4y
1
Thanks, it works really well now! Nowaha 459 — 4y
Ad

Answer this question