Kill a player if they move

So i’m fooling around with a survive the disasters kind of game and i’m wondering how I would make the game detect if a player is moving and kill them if they do. I have this code, but when the disaster begins, my studio starts freezing up like crazy.


while true do 
	for i, player in ipairs(game.Players:GetPlayers()) do
		local humanoid = player.Character.Humanoid

		humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
			if humanoid.MoveDirection.Magnitude > 0 then
				humanoid.Health = 0
			end
		end)

	end
end
2 Likes

You don’t need the while loop. You just have to do the for loop.

humanoid:GetPropertyChangedSignal("MoveDirection") will fire every time MoveDirection changes. So, you don’t need to check it every time. You just have to connect the function once for each player.

The reason your studio is freezing is because the script is running the same for loop over and over and over again, without ever stopping. Your studio is trying to wait for the script to finish running but it never does. Thus, freezing.

1 Like

You could also just check if the position has changed

You can use RunService.Stepped since it is a much more performant option and won’t crash studio. You can also use a for loop and loop through every player like this:

-- Server Script in ServerScriptService
-- Define the Service you are going to use
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This will run every frame prior to the physics simulation
RunService.Stepped:Connect(function()
    -- Loop through every player
    for Index, Player in ipairs(Players:GetPlayers()) do
        -- Get the Player's Character and Humanoid
        local Character = Player.Character or Player.CharacterAdded:Wait()
        local Humanoid = Character.Humanoid or Character:WaitForChild("Humanoid")
        -- Since this runs every frame we don't need to use GetPropertyChangedSignal
        if Humanoid.MoveDirection.Magnitude > 0 and Humanoid.Health > 0 then
            -- Checks if the player is moving and if they are not dead
            Humanoid.Health = 0
        end
    end
end)

Render Stepped is not needed. The checking if the MoveDirection was changed.

You don’t have a task.wait() in your while true do loop.
You’re overloading your CPU in test mode, and playing on the site would crash too.

EDIT, missed the fact that @ScelarSpectre already mentioned this.