I can’t seem to figure out how I would make a system that keeps track of how long it has been since a player was hit, my first assumption was to use 2 tick() variables and do the classical time1 - time2 = time difference but I’m assuming I have either used this technique wrong or there’s a more efficient way of achieving my goal.
CODE EXPLANATION
I’m working on an iFrame system for my current project and I want it to function as follows:
Player hits enemy > Enemy can STILL be hit for X amount seconds > iFrames activate
I’ve got everything to do with iFrames and hit detection working but I simply can’t figure out how to go about tracking when the enemy was last hit and weather or not that time has been longer than X seconds…
in a nutshell, the way I was using tick() worked like this:
local oldTime
function hit(characterThatWasHit)
local hitTime = tick()
if oldTime and hitTime - oldTime <= 5 then
-- run some highlight and attribute code
else
-- player took too long and iframes activated code
end
oldTime = hitTime
end
(this is one of my first times using tick() as you could probably tell haha)
the issue with this code was the fact that it wouldn’t reset the time whenever the same enemy is hit.
maybe you can add a number value or number attribute in the model of every character, then instead of using the oldTime variable you can use the value for the specific character? would that work with your code?
So… after doing a bit more research on this I’ve figured out a way of tracking the amount of time that has passed by using RunService now that I think about it, that’s a pretty obvious way of getting this to work
So, to cure your curiosity, HERE is how it works:
local RunService = game:GetService("RunService")
lastTouchedTime = math.huge -- we get math.huge here so that RunService doesn't actually do anything until we've updated this time value to something that passes the if statement inside of said RunService event
debounce = false
script.Parent.Touched:Connect(function(otherPart) -- this is just a basic "Part.Touched" example
if otherPart.Parent:FindFirstChild("Humanoid") and debounce == false then
debounce = true
script.Parent.BrickColor = BrickColor.Green()
lastTouchedTime = tick() -- every time a player touches this part, we update the time variable which tells us the most recent time a player touched this part
task.wait(1)
script.Parent.BrickColor = BrickColor.White()
debounce = false
end
end)
RunService.Heartbeat:Connect(function(deltaTime) -- RunService runs based on FPS (frames per SECOND)
if tick() - lastTouchedTime > 2 then -- we get the current time every single Heartbeat (or every frame AFTER the physics simulation has completed) and we compare the difference of the time that we last touched the part!
print("player has not touched part in over 2 seconds")
end
end)
So with this info you should hopefully have learnt something new and also be able to see how I can make my code work with this! No need to add any Values or Attributes!