Prevent the player from bumping into walls

Here’s the idea:

I have a toggle sprint system with a custom animation, but there’s a problem.

When I bump into a wall, the animation just keeps repeating, creating an unrealistic perspective.

How can I make it so the player just stops moving if they are bumping into a wall? Here’s my current script if needed:

local UserInputService = game:GetService("UserInputService")
local ContextActionService = game:GetService("ContextActionService")
local TweenService = game:GetService("TweenService")

local CurrentCamera = workspace.CurrentCamera

local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid", true)

local Animation = Humanoid:WaitForChild("Animator", true):LoadAnimation(script:WaitForChild("Run"))
Animation.Priority = Enum.AnimationPriority.Action

local TweeningInfo = TweenInfo.new(0.3, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)

local Running = script:WaitForChild("Running")

function Run(ActionName, InputState)
	if ActionName == "RunBind" and InputState == Enum.UserInputState.Begin then
		if Running.Value == false then
			Running.Value = true
			
			if Humanoid.MoveDirection.Magnitude > 0 then
				Animation:Play(0.2)
			end
			
			TweenService:Create(CurrentCamera, TweeningInfo, {FieldOfView = 80}):Play()
			Humanoid.WalkSpeed = 20
		elseif Running.Value == true then
			Running.Value = false
			
			Animation:Stop(0.2)
			TweenService:Create(CurrentCamera, TweeningInfo, {FieldOfView = 70}):Play()
			Humanoid.WalkSpeed = 10
		end
	end
end

ContextActionService:BindAction("RunBind", Run, false, Enum.KeyCode.LeftControl)

Humanoid.Running:Connect(function()
	if Running.Value and Humanoid.MoveDirection.Magnitude > 0 then
		Animation:Play(0.2)
		Humanoid.WalkSpeed = 20
	else
		Animation:Stop(0.2)
		Humanoid.WalkSpeed = 10
	end
end)

Humanoid.Jumping:Connect(function()
	if Animation.IsPlaying then
		Animation:Stop()
	end
end)

Thanks.

1 Like