Detect if part1 collided with part2 using script

Is it possible to detect if 2 parts collided or touch each other?

local p1 = game.Workspace.Part1
local p2 = game.Workspace.Part2

while wait() do
	p1.Touched:Connect(function()
		p2.Touched:Connect(function()
			print("p1 and p2 collided")
		end)
	end)
end

this is my script but this script doesn’t really emphisize p1 and p2 colliding with each other can you help me determine using a script if those parts collided with each other

Roblox has a BasePart:GetTouchingParts function.
https://developer.roblox.com/en-us/api-reference/function/BasePart/GetTouchingParts

1 Like

–A little background knowledge
Events are a little difficult to understand. When you connect an event it is basically setting a value of the event to the function you want. When the system sees that event has gone off it looks for that function.
–Problem
You only need to connect a function once. Connecting a function lasts until you disconnect it so nesting connections like this will not work. The Touched event has a value that it returns named hit. Hit is the part that the main part hit.
–Solution

local p1 = game.Workspace.Part1
local p2 = game.Workspace.Part2

p1.Touched:Connect(function(hit)
 if (hit == p2) then
  print("p1 and p2 collided")
 end
)
p2.Touched:Connect(function(hit)
 if (hit == p1) then
  print("p1 and p2 collided")
 end
)

Good luck!

2 Likes