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

How to make keypress only work when you're close to something?

Asked by 5 years ago
Edited 5 years ago

I'm trying to make a door that opens when you press the letter f on your keyboard. But I need it to open when you're close to it not when you're far away. Can anyone help me on this? The script is

local m = game.Players.LocalPlayer:GetMouse()
db = true
m.KeyDown:connect(function(k)
    k = k:lower()
    if k == "f" then
        if db == true then
            game.Workspace.Door.CanCollide = false
            game.Workspace.Door.Transparency = 1
            wait(3)
            game.Workspace.Door.CanCollide = true
            game.Workspace.Door.Transparency = 0.5
        end
    end
end)
0
region 3? OBenjOne 190 — 5y
0
I want to see the answer to this myself :) OBenjOne 190 — 5y
0
use :Connect plssssssss LoganboyInCO 150 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Magnitude is probably your best bet.

local Door = workspace.Door
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local ActivationDistance = 10
local OpenTime = 5

while true do
    local Input = UserInputService.InputEnded:wait()
    if Input.UserInputType == Enum.UserInputType.Keyboard then
        if Input.KeyCode == Enum.KeyCode.F then
            local CharacterPositionProbe = {pcall(function()
                return(Players.LocalPlayer.Character:GetPrimaryPartCFrame().p) 
            end)}
            if CharacterPositionProbe[1] and typeof(CharacterPositionProbe[2]) == "Vector3" then
                if (CharacterPositionProbe[2]-Door.Position).magnitude <= ActivationDistance then
                    Door.Transparency = 1
                    Door.CanCollide = false
                    wait(OpenTime)
                    Door.Transparency = .5
                    Door.CanCollide = true
                end
            end
        end
    end
end
0
thank you sorry for replying 1 year later HasansWorld12 2 — 3y
Ad

Answer this question