Code should work but doesn't, am I doing something wrong?

Hi, the goal I’m trying to achieve with this script is to make a player explode if their walk speed goes below 5.
I thought this code would work but since it doesn’t I’m assuming I did something wrong. If anyone could point out any errors I would greatly appreciate it.

local player = game:GetService("Players").LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")

local safe = true

local function AreYouSafe()
	if humanoid.WalkSpeed > 5 then
		safe = true
	elseif humanoid.WalkSpeed < 5 then
		safe = false

		local bomb = Instance.new("Explosion",workspace)
		bomb.BlastRadius = 16
		bomb.BlastPressure = 500000
		bomb.Position = character.HumanoidRootPart
		wait(1)
		bomb:Destroy()
	end
end

while task.wait() do
	AreYouSafe()
end

Thank you in advance

1 Like

The player’s walk speed is just the speed that they will go when walking. If you want to detect if they player goes under a certain speed, calculate the HumanoidRootPart’s velocity.

You can do this to get the velocity:

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")

local safe = true

local function AreYouSafe()
	local velocity = (character.HumanoidRootPart.Velocity * Vector3.new(1,0,1)).Magnitude -- Gets the character's velocity
	if velocity > 5 then
		safe = true
	elseif velocity <= 5 then
		safe = false

		local bomb = Instance.new("Explosion",workspace)
		bomb.BlastRadius = 16
		bomb.BlastPressure = 500000
		bomb.Position = character.HumanoidRootPart
		wait(1)
		bomb:Destroy()
	end
end

while task.wait() do
	AreYouSafe()
end

EDIT: You might have to adjust the minimum values as I’m not sure if velocity is the same as player WalkSpeed. Just play around with it until it works how you want it to

EDIT 2: Also, use the explosion in a RemoteEvent so it replicates across the server. That way you will actually die in the server and not bug the game. I recommend reducing the BlastPressure to 0 and just killing the player manually by doing humanoid:TakeDamage(10000)

2 Likes

Basically, the character isn’t loaded in when you assign the variable. To fix this without changing the script, do this for the character variable:
local character = game.Players.LocalPlayer.Character or game.Players.LocalPlayer.CharacterAdded:Wait()

2 Likes

Ah, I didn’t catch that. I’ll make an edit to my post

1 Like