Having trouble understanding my own sword script

I’m having trouble understanding how my sword script works, mostly the part that I’ve shown below. I don’t really remember what I was doing to get it to work and I don’t really understand what I wrote, basically, Im making a sword script that handles hit detection on the client and then the server will verify every hit that they make (via a RemoteEvent). Basically, the 0.7 is just a placeholder for the duration of the whole swing (the time period that they can hit enemies in). So on the server, I made this canAttack variable which is based on that swing duration, but somehow I can’t really understand what I did to make it work, so if anyone can provide some context, it would be great so I just know how I got to this point.

	local taggedHumanoids = {}
	
	if targetHumanoid then
		if taggedHumanoids[targetHumanoid] then -- Ensures the same humanoid cannot be hit twice during a single attack.
			return false
		end
	end
	if not canAttack then
		if math.abs(os.clock() - lastHit) >= 0.7 then
			canAttack = true
			lastHit = os.clock()
			
			task.delay(0.7, function()
				canAttack = false
				taggedHumanoids = {}
			end)
		end
	else
		taggedHumanoids[targetHumanoid] = true
		targetHumanoid:TakeDamage(30)
	end
end

Ideally, my goal with the lastHit and canAttack was to make it so that exploiters cant attack super fast WITHOUT removing the player’s ability to damage multiple enemies in one swing, I just don’t understand how the code itself works.

Based on the script you have sent, This is what i understand

  • at the very start, you have tagged humanoids which were already hit to prevent damaging again
  • when you cant attack, you’re checking if time has passed using maths abs which makes the negative number a positive number.
  • When the time did pass, youre setting can attack to true and and updating the last hit.
  • you’re using task.delay where after 0.7 milseconds youre reseting taggedhumanoids and setting can attack false
  • if can attack if is false, it set taggedhumanoid to true and then damages the humanoid

This is how it works.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.