Efficiently detecting if a player is touching a part

I am making a shop that activates when you touch a part. The script works by detecting when the player’s head touches an activation part and activates a remote event telling the client to tween the gui. The client sided script works fine, however, the server sided one sends out lots of signals at the wrong times. I have been thinking about ditching the .touched() event for using Magnitude to detect the player. Should I do this, and if I should, could you tell me how?

Here is the server-sided script:


local debounce = false

game.Workspace.TrailsTouch.Touched:Connect(function(hit)
	print("e")
	if debounce == false then
		if hit.Name == "Head" then
			print("e")
			debounce = true
			wait()
			print("e")
				print("e")
				game.ReplicatedStorage:WaitForChild("TweenTrailsUI"):FireClient(game.Players:GetPlayerFromCharacter(hit.Parent), "Up")
				workspace.TrailsTouch.TouchEnded:Connect(function(hit)
				game.ReplicatedStorage:WaitForChild("TweenTrailsUI"):FireClient(game.Players:GetPlayerFromCharacter(hit.Parent), "Down")
			end)
		wait(0.8)
		debounce = false
		end
	end
end)

Here is the client sided script:

local players = game:GetService("Players")
local playerGUI = players.LocalPlayer:WaitForChild('PlayerGui')
local trailGui = playerGUI:WaitForChild("EquipTrails")
local ui1 = trailGui:WaitForChild("ScrollingFrame")
local ui2 = trailGui:WaitForChild("Background")
local replicatedStorage = game:GetService("ReplicatedStorage")
local remote = replicatedStorage:WaitForChild("TweenTrailsUI")

remote.OnClientEvent:Connect(function(direction)
	if direction == "Up" then
		ui1:TweenPosition(UDim2.new(0.272, 0,0.27, 0), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.2, false)
		ui2:TweenPosition(UDim2.new(0.5, 0,0.6, 0), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.2, false)
		print(ui1.Name)
		print(ui2.Name)
		print('tweened')
	else
		ui1:TweenPosition(UDim2.new(0.272, 0,1, 0), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.2, false)
		ui2:TweenPosition(UDim2.new(0.5, 0,1.5, 0), Enum.EasingDirection.InOut, Enum.EasingStyle.Sine, 0.2, false)
		print('tweened2')
	end
end)

The .Touched function is a very bad way to detect if a player touched something on my opinion - sometimes it works, sometimes it doesn’t. Honestly, I don’t know any other ways but you could try the ZonePlus module made by a developer: ZonePlusModule
I’m not sure if that works though, I never really used ZonePlus and yeah, but you could at least try. Hope this helped!

1 Like

use players:GetPlayerFromCharacter(character) and check if the thing it touches has a humanoid with if hit.Parent:FindFirstChildOfClass("Humanoid") then

Its really useful. Roblox should implement a better way of detecting collisions

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.