Reputation: 1327
I am coding an obby on Roblox Studio. In this obby, I have parts that the character jumps on (the parts are roughly 10 by 10 studs).
I want to achieve that whilst the character is on a part, that part changes color.
local platform = script.parent
local function changeColor(part)
local humanoid = part.Parent:FindFirstChild(‘Humanoid’)
if humanoid then
part.BrickColor = BrickColor.new(‘Bright red’)
end
end
local function restoreColor(part)
local humanoid = part.Parent:FindFirstChild(‘Humanoid’)
if humanoid then
part.BrickColor = BrickColor.new(‘Grey’)
end
end
platform.Touched:connect(changeColor)
platform.TouchEnded:connect(restoreColor)
The problem with this, is that as the character walks on the part, the part changes from grey to red and back with each step. I want the part to remain red for the duration of the player being on it. So I want the function to check whether the player has walked on it in the last say .5 seconds, to give the player time to walk without reverting the color. Is this the right approach, and if so how would I go about it. Is it possible to override the touched function?
Here is what it looks like (I later changed the code a bit, including color etc... but the fundamental problem remains)
Upvotes: 3
Views: 1986
Reputation: 43
Use a debounce. A debounce stops events or functions from running too quickly.
local debounce=true
local part=script.Parent
local function changecolor()
if debounce then
debounce=false
-- add color changing code here
task.wait(2)
debounce=true
Part.Touched:Connect(changecolor)
This makes the function only be able to run once every two seconds.
Upvotes: 0
Reputation: 425
You could try using the IsRegion3Empty function, which should more reliably return whether there are any players standing directly above the platform. It has two advantages:
It can be adjusted to be less sensitive than Touched
and TouchEnded
, since direct contact with the platform isn't required, as long as the player is within some small region above the platform.
It can handle multiple players. If you were to connect TouchEnded
to resetting the color, then if two players stand on the platform, and one leaves, the color will be reset even when a player is still standing on it. By checking if the region above the platform is empty, the color will only be reset when all players leave the platform.
The above method will trigger when any parts enter the region. To limit it to players, you can instead use the FindPartsInRegion3 function and check if the part has a Humanoid parent.
Upvotes: 2