Help With Touch Event

Basically I want it whenever the player clicks their mouse, it will then check if the player is touching a specific part/hitbox. If so it will fire the function if not it will do nothing. However, with my current script, whenever the character clicks their mouse when they aren’t touching the specific part and once they come into contact with the specific part, it fires the function.

local rp = game:GetService("ReplicatedStorage")
local Spike = rp:WaitForChild("Events").Spike

Spike.OnServerEvent:Connect(function(player, MouseHit) 
	local char = player.Character
	local root = char.HumanoidRootPart
	local playerhitbox = char.PHitBox
	local humanoid = char.Humanoid
	local touched = player.Backpack.Touched
	local effect = script.Effect
	
	local animationevent = rp.Animation.Spike

	local connection

	local function hit(part)
		
		if part.Name == "Hitbox" then
			touched.Value = true

			
			local ball = part.Parent 
			local Velocity = Instance.new("BodyVelocity")
			local Force = 50
			
			local Direction = MouseHit.Position - ball.Position

			local sound = effect:Clone()
			sound.Parent = ball
			sound:Play()

			Velocity.Parent = ball
			Velocity.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
			Velocity.Velocity = (Direction.Unit * Force * 1.5) --+ Vector3.new(0, Force/10 , 0)--(Direction.Unit * Force/2.5) + Vector3.new(0, Force * .75 , 0)

			game:GetService("Debris"):AddItem(Velocity, 0.1)
			game:GetService("Debris"):AddItem(sound, 2)
			
			connection:Disconnect()
			
			wait(1)
			touched.Value = false
		end
	end
	if player.Backpack.Touched.value == false then
		connection = playerhitbox.Touched:Connect(hit) 	
	end
end)
1 Like

:GetTouchingParts might actually be what you’re looking for given that it just gives you a list of parts touching another part on that frame. which you could just do on all body parts to find if something is touching the player model.

But I wouldn’t actually do that, because it has the same problem with “:GetTouched”. If you jump on a part it sometimes doesn’t detect it. so instead I might do something like this

find_part = Instance.new("Part")
find_part.Size = Vector3.new(2, 2.25, 1)
find_part.CanCollide = true
find_part.Anchored = true
find_part.Parent = game.Workspace
find_part.CFrame = player_c.Torso.CFrame + Vector3.new(0,-2,0)
local parts = find_part:GetTouchingParts()
Is_Spike = false
for number,part in pairs(parts) do
    if part.Name == "Spike" then
        Is_Spike = true 
    end
end
if Is_Spike == true then
  -- continue your code here
end

That script created a part which around the player’s legs, which extends 0.25 studs below the legs. The part detects if it’s touching anything and loops through all the parts that it is touching. If it finds a spike, it continues with the code.