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

How to detect distance from player to object?

This is the current method im using. I'm trying to make a door you have to click "E" to open but I want it so you have to be in range of that door. I am current being faced with the error: "Workspace.Mdoor.Union.Script:5: bad argument #2 to '?' (Vector3 expected, got Object)"

The scripts are below. If anyone knows what im doing wrong and can help me that would be nice :D

Class: LocalScript

local UserInputService = game:GetService("UserInputService")
local rs = game:GetService("ReplicatedStorage")
local r = rs.Remotes:WaitForChild("DoorOpen1")
local plr = game.Players.LocalPlayer
local character = plr.Character or plr.CharacterAdded:Wait()
local HRP = character:WaitForChild("HumanoidRootPart").Position

local function key(inputObject, gameProcessed)
	if inputObject.KeyCode == Enum.KeyCode.E then
		r:FireServer(HRP)
	end
end

UserInputService.InputBegan:Connect(key)

Class: Script

local rs = game:GetService("ReplicatedStorage")
local r = rs.Remotes:WaitForChild("DoorOpen1")

r.OnServerEvent:connect(function(HRP)
	if (script.Parent.Position - HRP).magnitude <= 3 then
		print(r.Name.. " was fired!")
		local door = game.Workspace.Mdoor:WaitForChild("Union")
		local hinge = game.Workspace.Mdoor:WaitForChild("Hinge")
	
		local hingep = hinge.Position

		for i = 1, 120 do
			door.CFrame = CFrame.new(hingep)* CFrame.Angles(0,math.rad(i),0) * CFrame.new(0.294,0,2.89500)
			wait()

		end
	end
end)

3 comments

0

seems like you forgot to do HRP.Position buddy. :^)

0

@WaterIsIceSoup HRP is a vector3 value

0

@WaterIsIceSoup also I did. HRP was defined as '.HumanoidRootPart.Position

1 answer

✓ Accepted answer

You are getting this error because .OnServerEvent first returns the player firing the event and then the rest of the parameters you are passing along.

To fix this we simply account for it giving us player

local rs = game:GetService("ReplicatedStorage")
local r = rs.Remotes:WaitForChild("DoorOpen1")

r.OnServerEvent:connect(function(player,HRP)
    if (script.Parent.Position - HRP).magnitude <= 3 then
        print(r.Name.. " was fired!")
        local door = game.Workspace.Mdoor:WaitForChild("Union")
        local hinge = game.Workspace.Mdoor:WaitForChild("Hinge")

        local hingep = hinge.Position

        for i = 1, 120 do
            door.CFrame = CFrame.new(hingep)* CFrame.Angles(0,math.rad(i),0) * CFrame.new(0.294,0,2.89500)
            wait()

        end
    end
end)

Also, I don't know if it's suppose to be like this but in your localscript you are setting HRP when the script loads. You may want to set that variable when the key function is ran so you get the character's current position.

1 comment

0

Thanks man.

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