Hey, I am writing a system that, depending on whether the player (with its root part) is currently touching a “hitbox” by using the Touched and TouchEnded events, they will be able to perform an action. The catch is, the Part will constantly be changing its CanTouch value from true to false.
Since the part cannot be touched anymore, even if the player is currently touching the part, you’d assume TouchEnded would be fired to signify that the player is no longer touching the part. But, as it turns out, the player is still considered to be “touching” the Part even if its CanTouch value is set to false and won’t fire TouchEnded.
Is this a bug or is this feature intended to be this way?
I do not think this is a bug, as how touch event works, by disabling cantouch, you’re disable both touched and touchedended events. So even if the player or anything is still touching the part while cantouch is disabled, its logical that touchended wouldn’t fire. (it’s just my opinion i recommend you wait for a while until you get other’s programmers/scripters opinions about this case)
When CanTouch is false, the part essentially stops registering new touch events. This means it doesn’t trigger TouchEnded for existing touches because the part is no longer actively tracking collisions (Summarized what @lamcellari was saying). If you want to control when a part can be touched or not you should add a control variable on top of your logic sort of like a gate in a dam.
Example:
local Part:Part;
local CanBeTouched = true
local function TouchStart()
if not CanBeTouched then return end
--Touch start logic
end
local function TouchEnd()
if not CanBeTouched then return end
--Touch ended logic
end
Part.Touched:Connect(TouchStart)
Part.TouchEnded:Connect(TouchEnd)
Feels a bit counter intuitive, I thought it would fire TouchEnded as soon as it stopped registering touches.
Sadly I cannot implement your approach as it’s 2 different scripts doing the attribute change (setting CanTouch to false) and the checking of touched events.I’ll probably devise a plan using attributes or the .Changed event. Thanks for taking the time to provide the code example either way!