How I do enter and exit collision?

I want an event to fire once when Player is in collision with some part and then again when it exits the collision. Can I do this in Roblox? For now I just know touched event, that is firing as long the collision is happening.

You can use the TouchEnded Event to tun something as soon as the collision has stopped.
E.g.

local part = workspace.part --Assuming it's in workspace
Part.TouchEnded.Connect(function()
---Do what you want
end)

My biggest problem is, when Player moves inside the collision box, the touched event fires again and again.

You can create a table and place the player’s username or userid into the table and then check that table when the touched event fires so that if they’re already in the table the function wont apply again, and then you can do TouchEnded and refer back to the table to remove them, but ensure you put a debounce in there and a slight time delay at the end so it doesn’t immedietly fire touched again.

Something like…

local TouchTbl = {}
local part = game.workspace.SomePart
part.Touched:Connect(function(partTouched)
if partTouched.Parent:FindFirstChild("Humanoid") then
    local exists = table.find(TouchTbl, partTouched.Parent.Name)
    if not exists then
        table.insert(TouchTbl, partTouched.Parent.Name)
    end
end
end)

part.TouchEnded:Connect(function(partTouched)
    if partTouched.Parent:FindFirstChild("Humanoid") then
        local exists = table.find(TouchTbl, partTouched.Parent.Name)
        if exists then
           wait(.5)
           table.remove(TouchTbl, partTouched.Parent.Name)
       end
    end
end)

You could also add in both touched and touchEnded a check for a specific body part before adding or removing from the table to get a little more fine tuned.

2 Likes

I think it’s better to either approach this using Region3 or constant raycasting. Alternatively, you can still use Touched, but the solution is different:

1 Like