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

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

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)

3 comments

0

region 3?

0

I want to see the answer to this myself :)

0

use :Connect plssssssss

1 answer

✓ Accepted answer

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

1 comment

0

thank you sorry for replying 1 year later

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