Help with anchor when not moving script

I’m trying to make a script that anchors the player when he’s not moving, but when the player jumps the script ends up anchoring the player in the air …
To close this post I need to correct this.

local function checkMovement(): boolean
	for i, keys in pairs(keysPressed) do
		if keys == true then
			return true
		else end
	end
	return false
end

local function anchorHumanoidRootPart()
	
	while true do
		task.wait()
		local moving = checkMovement()
		if moving == true then
			hrp.Anchored = false
		else
			task.wait(0.1)
			if isJumping == false then
				hrp.Anchored = true
			end
		end
	end
end

uis.InputBegan:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.W or inputObject.KeyCode == Enum.KeyCode.D or inputObject.KeyCode == Enum.KeyCode.S or inputObject.KeyCode == Enum.KeyCode.A or inputObject.KeyCode == Enum.KeyCode.Space then
		print(inputObject.KeyCode)
		print(inputObject.KeyCode.Value)
		keysPressed[tostring(inputObject.KeyCode)] = true
	end
end

uis.InputEnded:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.W or inputObject.KeyCode == Enum.KeyCode.D or inputObject.KeyCode == Enum.KeyCode.S or inputObject.KeyCode == Enum.KeyCode.A or inputObject.KeyCode == Enum.KeyCode.Space then
		keysPressed[tostring(inputObject.KeyCode)] = false
	end
end

humanoid.Jumping:Connect(function(isActive)
	if isActive then
		isJumping = true
		print(isJumping)
	else
		isJumping = false
		print(isJumping)
	end
end)
2 Likes

According to the documentation for Humanoid.Jumping:

When a Humanoid jumps, this event fires with an active parameter of true before shortly afterwards firing again with an active parameter of false. This second firing does not correspond with a Humanoid landing; for that, listen for the Landed Enum.HumanoidStateType using Humanoid.StateChanged.

This means that in the last function, isJumping is being set to false before the player’s Character lands, meaning that the conditional statement within the anchorHumanoidRootPart function that checks if isJumping == false is able to set the HumanoidRootPart to false while the Character is mid-air.

To resolve this, consider replacing the function activated by Humanoid.Jumping with Humanoid.StateChanged.

Example revision:

humanoid.StateChanged:Connect(function(oldState, newState)
    if newState == Enum.HumanoidStateType.Jumping then
        isJumping = true
    elseif newState == Enum.Humanoid.StateType.Landed then
        isJumping = false
    else
        print("newState was neither 'Jumping' or 'Landed'")
        -- Consider also setting isJumping to false here if you encounter issues (but this means it would also trigger it upon entering states such as "Freefall")
    end
end)
3 Likes

How come I didn’t think of that… that’s it! <3

1 Like

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