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

Check distance between Player and Object ( Model ) better ways?

So the idea behind this is so when you spawn a car that it only shows for the local player ( who spawned it ) a Billboard Gui which says "Your Car" above it.

It works great right now and everything works.

But im constantly checking with a while true do loop if the distance between player and car is greater or less. I think this is pretty performance heavy with like 20 people ingame. Is this correct? is there a better way to handle this?

Sidenote: Billboardgui is placed in playergui : Here is the localscript which is inside

local player = game.Players.LocalPlayer

local trigger = false

while wait(0.5) do
local dist = player:DistanceFromCharacter(game.Workspace:WaitForChild(player.Name.."-Car").PrimaryPart.Position)
print(dist)
	if dist < 30 then
		script.Parent.Adornee = nil
		script.Parent.Enabled = false
		trigger = true
	else
		if trigger == false then
		script.Parent.Adornee = game.Workspace:WaitForChild(player.Name.."-Car")
		script.Parent.Enabled = true
		end
	end
end

This is the function where I fire my remoteevent to spawn the car and adornee the billboard

box.MouseButton1Click:Connect(function()
		game.ReplicatedStorage.Events.CarShop.SpawnCar:FireServer(availableCars[i][1])
		
		--Function to show Billboard Gui above car
		wait(1)
			showcarpos.Enabled = true
			showcarpos.Adornee = game.Workspace:WaitForChild(player.Name.."-Car")

		end)
	end
end)

Other side note. The players car gets called "Player1-Car" etc. So after the players, if that helps.

2 comments

1

You could surround the car in a region3 and have your script fire when the local player enters the region3 (within 30 of the car). This prevents the constant need to check the player's position.

0

good Idea, I'll try that.

1 answer

Just a side tip, you can use magnitude to check distance (In case character is not involved):

local distance = (game.Players.LocalPlayer.Character.HumanoidRootPart.Position-game.Workspace:WaitForChild(player.Name.."-Car").PrimaryPart.Position).Magnitude

1 comment

0

Thanks! :))

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