How do I run a function only when the user is close to the door?

I want to create a basic script. How do I make it so that if the Player is close to the door, make this function run. If the Player is far away from the door, do not run the function.

3 Likes

You can use magnitude to get the distance between the player and the door.

local DISTANCE_TO_DOOR = 10

local function isCloseEnoughToDoor(player, door)
--//Assign some random part in the door to be the PrimaryPart of the model
return (player.PrimaryPart.Position - door.PrimaryPart.Position) <= DISTANCE_TO_DOOR
end

if isCloseEnoughToDoor(workspace.C_Sharper, workspace.someDoor) then
--//execute some code
end
2 Likes

C_Sharper is not a valid member of Workspace “Workspace” - Client - LocalScript:17

C_Sharper is his name. Just change it to something else

1 Like

ALSO, Primary Part is not part of Workspace.Model.Door

It’s unclear what I need to do. It just keeps shooting out bugs.

Look at the Properties of the Door Model. There is one that says PrimaryPart. Click that line and then select a Part in your door that you want as the Primary Part. It’ll auto-fill that Part into the PrimaryPart property.

1 Like

It’s not a group. It’s just a part

Do you have the Door as a Model? If not just make the group of Parts a Model.

Done. Now how do I detect if the Player is near it? The variables are assigned already

That’s what the script does, it detects if the player PrimaryPart is 10 studs or less away from the Door Primary Part.
Where @C_Sharper put --//execute some code put in the code you want to happen when the player is 10 studs from the door.

1 Like

Yes, but C_Sharper isn’t a valid member of Workspace, what do I replace it with? The player?

And AGAIN. I set the primary part, LIKE YOU SAID, and it still says " PrimaryPart is not a valid member of Part “Workspace.Model.Part”

That’s because you made the script look for PrimaryPart of a part - it doesn’t exist so just chage the path to model.

Model is not a valid member of Part “Workspace.Model.Part”

And you need to use a server script.

I can’t because it’s a password system

workspace.Model.PrimaryPart

Players.TheFreeScriptDev.PlayerGui.PasswordGUI.InputDetector.LocalScript:13: attempt to perform arithmetic (sub) on Instance

Sigh.

Can you show your current code?