Help With Touch

I am trying to make a script where if a ball hits a part a particle goes off. I have to parts and the script is located in ServerScriptServices

The problem is both parts’ particles go off

How do I fix this

-- SERVER SCRIPT LOCATED IN SERVERSCRIPTSERVICES
-- Get references to the ball and particle effects
local ball = workspace.Ball
local partO = workspace.PartO
local partB = workspace.PartB
local ballSpawn = workspace.BallSpawn
local particle1 = partO.Attachment.ParticleEmitter
local particle2 = partB.Attachment.ParticleEmitter

function onTouchO()
	if (ball ~=nil) then
		-- Turn on the particle effect for PartO
		particle1:Clear()
		particle1:Emit(10)
		wait(1)
		-- Disable the ball's visibility for Part)
		ball.Position = ballSpawn.Position
		ball.Transparency = 1
		ball.Highlight.OutlineTransparency = 1
		task.wait(3)
		ball.Transparency = 0
		ball.Highlight.OutlineTransparency = 0
	end
end

function onTouchB()
	if (ball ~=nil) then
		-- Turn on the particle effect for PartB
		particle2:Clear()
		particle2:Emit(10)
		wait(1)
		-- Disable the ball's visibility for Part)
		ball.Transparency = 1
		ball.Highlight.OutlineTransparency = 1
	end
end

ball.Touched:Connect(onTouchO)
ball.Touched:Connect(onTouchB)
1 Like

You’re assinging two functions for when the ball is being touched but you didn’t specify which part the ball is touching.

Try making one function with two conditions instead:

local db = false

function onTouch(hit)
	
	if hit.Name == "PartO" then
		
		if (ball ~=nil) then
			-- Turn on the particle effect for PartO
			if db then return end
			db = true
			particle1:Clear()
			particle1:Emit(10)
			wait(1)
			-- Disable the ball's visibility for Part)
			ball.Position = ballSpawn.Position
			ball.Transparency = 1
			ball.Highlight.OutlineTransparency = 1
			task.wait(3)
			ball.Transparency = 0
			ball.Highlight.OutlineTransparency = 0
			db = false
		end
		
	elseif hit.Name == "PartB" then
		
		if (ball ~= nil) then
			if db then return end
			-- Turn on the particle effect for PartB
			db = true
			particle2:Clear()
			particle2:Emit(10)
			wait(1)
			-- Disable the ball's visibility for Part)
			ball.Transparency = 1
			ball.Highlight.OutlineTransparency = 1
			db = false
		end
		
	end

end

ball.Touched:Connect(onTouch)

Side note: Touched event will probably need a debounce so that it doesn’t fire multiple times very quickly from different parts on a player or other object touching it.

1 Like