When considering collision handling on parts, note the following:
- A part's CanCollide property affects whether it will physically collide with other parts and cause forces to act upon them.
- Even if CanCollide is disabled for a part, you can detect intersection and un-intersection through collision events.
The Touched event fires when a part comes in contact with another part. It only fires as a result of physical simulation and will not fire when the part's Position or CFrame is explicitly set such that it overlaps another part.
The following code pattern shows how the Touched event can be connected to a custom onTouched function. Note that the event sends the otherPart argument to the function, indicating the other part involved in the collision.
1local part = workspace.Part23local function onTouched(otherPart)4 print(part.Name .. " collided with " .. otherPart.Name)5end67part.Touched:Connect(onTouched)8
The TouchEnded event fires when the entirety of a part exits the collision bounds of another part. It only fires as a result of physical simulation and will not fire when the part's Position or CFrame is explicitly set such that it stops overlapping another part.
1local part = workspace.Part23local function onTouchEnded(otherPart)4 print(part.Name .. " is no longer touching " .. otherPart.Name)5end67part.TouchEnded:Connect(onTouchEnded)8
Models such as player characters contain multiple parts. Since a model as a whole cannot be connected to the Touched or TouchEnded events, you'll need to loop through its children and connect the custom onTouched function to each child BasePart.
1local model = workspace.Model23local function onTouched(otherPart)4 -- Ignore instances of the model coming in contact with itself5 if otherPart:IsDescendantOf(model) then return end67 print(model.Name .. " collided with " .. otherPart.Name)8end910for _, child in pairs(model:GetChildren()) do11 if child:IsA("BasePart") then12 child.Touched:Connect(onTouched)13 end14end15
In most cases, the Default setting is suitable, but other settings can be selected based on best performance (Hull or Box) versus accuracy (PreciseConvexDecomposition).