I wrote this script for an NPC, the clicked method is linked to a click detector. The debounce does not work. I have tried checking before I call :Clicked but that didnt work
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local brainrotModels = ReplicatedStorage:WaitForChild("BrainrotModels")
local moneyModels = brainrotModels:WaitForChild("MoneyModels")
local cashModel = moneyModels:WaitForChild("Cash")
local spawnPoint = workspace.BrainrotSpawn
local module = {}
module.__index = module
local config = {
MaxRandomMoveDistance = 20,
RaycastLength = 22,
WalkSpeed = 7,
MoneyOffset = Vector3.new(0,1,4),
JumpPower = 0,
ClickDebounceTime = 1
}
function module.new(age,model)
local self = setmetatable({},module)
self.Model = model:Clone() :: Model
self.Humanoid = self.Model:FindFirstChild("Humanoid")
self.Age = age
self.State = "Idle"
self.IsClicked = false
--spawning
self.Model:PivotTo(spawnPoint.CFrame)
self.Model.Parent = workspace
--getting click detector
local descs = self.Model:GetDescendants()
for _, inst in descs do
if inst:IsA("ClickDetector") then
self.ClickDetector = inst
elseif inst:IsA("BasePart") then
inst.CanCollide = false
end
end
--setup
self.Humanoid.WalkSpeed = config.WalkSpeed
self.Humanoid.JumpPower = config.JumpPower
return self
end
function module:DropMoney(amount)
local origin = self.Model.PrimaryPart.CFrame * CFrame.new(config.MoneyOffset)
local newModel = cashModel:Clone()
newModel:PivotTo(origin)
newModel.BillboardGui.CashAmount.Text = "$"..tostring(amount)
newModel.Parent = workspace
end
function module:Clicked(amount)
if self.IsClicked then return end
print(self.IsClicked)
self.IsClicked = true
self:DropMoney(amount)
task.delay(config.ClickDebounceTime,function()
self.IsClicked = false
end)
end
function module:Raycast(position)
local origin = self.Model.PrimaryPart.Position
local dir = (position - origin).Unit * config.RaycastLength
local params = RaycastParams.new()
params.FilterDescendantsInstances = {self.Model}
params.FilterType = Enum.RaycastFilterType.Exclude
local ray = workspace:Raycast(origin,dir,params)
return ray
end
function module:MoveTo(postion)
if not postion then return end
self.Humanoid:MoveTo(postion)
self.State = "Walking"
self.Humanoid.MoveToFinished:Once(function()
self.State = "Idle"
end)
end
function module:MoveRandom()
if self.State ~= "Idle" then return end
local maxRandom = config.MaxRandomMoveDistance
local ranX = math.random(-maxRandom,maxRandom)
local ranZ = math.random(-maxRandom,maxRandom)
local origin = self.Model.PrimaryPart.Position
local finalTarget = origin + Vector3.new(ranX,0,ranZ)
local raycastedPos = self:Raycast(finalTarget)
if raycastedPos then
self:MoveRandom()
else
self:MoveTo(finalTarget)
end
end
function module:Poop()
self.State = "Pooping"
end
function module:Sleep()
self.State = "Sleeping"
end
function module:Eat()
self.State = "Eating"
end
return module
