I’m trying to get the player’s distance from a part to see if the can open a door or not but it doesn’t seem to want to work. Here is my code,
(variables)
local MiddlePos = script.Parent.Parent.Middle.Position local Distance = script.MaxDistance
(main code)
Plrs[Plr].CharacterAdded:Wait()
local PlayerPos = Plrs[Plr].Character:WaitForChild("Torso", 5).Position
if (MiddlePos - PlayerPos).Magnitude <= Distance.Value then
You could do
Player:DistanceFromCharacter(part.Position) something like that without needing to use magnitude checks on a certain bodypart(unless needed to for some cases)
but yeah it may need a loop or some event to connect the function to
Did you do what I told you to? Add print statements checking the values of the variables, read the output and look for errors, tell us them if you do get them.
It seems the Magnitude is too high, the if statement checks if the distance between the Player and the Part is lower than MaxDIstance (10), but the Magnitude is 349, meaning the condition is not met.
Did you mean to check if the distance is HIGHER than MaxDistance?
And the distance considered close enough is MaxDistance respectively? That rather means you’ll have to check if Distance <= CloseEnough (If the distance between Player and Part is equal to or lower than CloseEnough then pass on. (Execute))
I tried spawning at different places on the map and it seems it isn’t using the Torso’s position; The magnitude only changes when I move the actual door to a different position on the map.
You said that code is running in a loop? What part? CharacterAdded only fires once when the character is added. You need to have that wait outside of the loop and just calculate magnitude in the loop.
while true do
local Plrs = game.Players:GetChildren()
for Plr = 1, #Plrs do
Plrs[Plr].CharacterAdded:Wait()
local PlayerPos = Plrs[Plr].Character:WaitForChild("Torso", 5)
if (MiddlePos.Position - PlayerPos.Position).Magnitude <= Distance.Value then
InputService.InputBegan:Connect(function(Input, Received)
if Input.UserInputType == Enum.UserInputType.Keyboard then
if Input.KeyCode == Enum.KeyCode.E then
Tween1Open:Play()
end
end
end)
else
return
end
end
wait()
end
I am on a phone right now so this will just be psuedo code. Also it can be simpler to use the built in functions to do some of this. You don’t want to use player.Character added in a loop like that because if they don’t have a character you don’t need to check their distance. Here is an example:
while wait do
for i, player in players:GetPlayers() do
if player.Character then
if player:DistanceFromCharacter(thatPosition) < maxDistance then
end
end
end
end