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

Why doesn't this magnitude detection script work?

Asked by
wddfrt 21
4 years ago

The script is supposed to allow a shop GUI to be opened and closed when in a certain range of a part. I don't get any errors in output when testing the script either.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local Mag = (game.Workspace.Part.Position - player.Character:WaitForChild("HumanoidRootPart").Position).magnitude


mouse.KeyDown:Connect(function(key)
    if key == "e" then
        if Mag <= script.Parent.Range.Value then
    game.StarterGui.Gui.MainFrame.Visible = not game.StarterGui.Gui.MainFrame.Visible
    end
    end
end)

1 answer

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

The issue is that you never update Mag, the calculation is always only done once at the very top of the script. Instead, define Mag inside the event to prevent this.

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

mouse.KeyDown:Connect(function(key)
    if key == "e" then
    local Mag = (game.Workspace.Part.Position - player.Character:WaitForChild("HumanoidRootPart").Position).magnitude
        if Mag <= script.Parent.Range.Value then
    game.StarterGui.Gui.MainFrame.Visible = not game.StarterGui.Gui.MainFrame.Visible
    end
    end
end)

By doing this, the magnitude calculation runs every time you press the E key instead of just once at the very top of the script.

Additionally though this isn't needed, I'd recommend using UserInputService for any future work after this, it has several useful features that mouse.KeyDown doesn't have.

Ad

Answer this question