Sliding down slopes

I’ve been using raycast for the first time to develop a feature that lets players slide down slopes, however I’ve encountered a problem that needs fixing.
image

the script is as follows:

local character = game.Players.LocalPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local sliding = false

game:GetService("UserInputService").InputBegan:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Z then
		local ray = Ray.new(character.HumanoidRootPart.Position, Vector3.new(0, -1, 0))
		local hit, pos = workspace:Raycast(ray, Vector3.new(1))
		if hit and hit.Position.Y > 0.5 then
			sliding = true
		end
	end
end)

game:GetService("UserInputService").InputEnded:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Z then
		sliding = false
	end
end)

while true do
	if sliding then
		local velocity = -30

		humanoid.WalkSpeed = velocity

		while sliding do
			wait()
		end
	end

	wait()
end

There’s probably made a number of mistakes, so if anyone finds one, please let me know.

You are creating a ray twice and you’re setting the start position of the second ray to the first ray.

I don’t suggest you to use Ray.new(). It’s deprecated, you should do this instead:

local Result = workspace:Raycast(startposition, direction)

if Result then -- check if ray hit something, this prevents erroring
    -- you can check the ray's hit part material, position,
    -- the distance between the ray and the hit part and much more
    -- rest of the code here
end

Check out the documentations:

1 Like

Try this code, I fixed a lot of things, hopefully the math is right:

local character = game.Players.LocalPlayer.Character
local humanoid = character:WaitForChild("Humanoid")
local sliding = 0

game:GetService("UserInputService").InputBegan:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Z then
		local params = RaycastParams.new()
        params.FilterType = Enum.FilterType.Blacklist
        params.FilterDescendantsInstances = {character}
		local result = workspace:Raycast(character.HumanoidRootPart.Position, Vector3.new(0, -1, 0), params)
		if result and result.Hit and result.Hit.Position.Y > 0.5 then
			sliding = 30
		end
	end
end)

game:GetService("UserInputService").InputEnded:Connect(function(inputObject)
	if inputObject.KeyCode == Enum.KeyCode.Z then
		sliding = 0
	end
end)

game:GetService("RunServicde").RenderStepped:Connect(function(dt)
    if sliding <= 0 then sliding = 0 end
    if sliding > 0 then
        sliding -= dt
		humanoid.WalkSpeed = sliding
    else
        humanoid.WalkSpeed = 16
    end
end)
1 Like

thanks, but it doesn’t seem to be working? the player doesn’t really “slide” down or move at all when you press Z