Need help with lean script

I’ve been trying to make this script that makes the character lean left and right for a couple of hours now and I cant seem to get it to work properly you can lean right using e but left with q is completely unresponsive I would greatly appreciate some help.
Thank you.

--variables
local animationId = "6788950027"
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local animation = Instance.new("Animation")
animation.AnimationId = "rbxassetid://"..animationId
local animationTrack = humanoid:LoadAnimation(animation)
local AnimationIdf = "6788957751"
local Animation = Instance.new("Animation")
Animation.AnimationId = "rbxassetid://"..AnimationIdf
local AnimationTrack = humanoid:LoadAnimation(Animation)


--services
local UserInputService = game:GetService("UserInputService")
local tweenService = game:GetService("TweenService")

local ti = TweenInfo.new(
	
	0.2,
	Enum.EasingStyle.Sine
	
)

UserInputService.InputBegan:Connect(function(key, isTyping)
	if key.KeyCode == Enum.KeyCode.E then
		tweenService:Create(humanoid ,ti, {CameraOffset = Vector3.new(1.5,0,0)} ):Play()
		if not animationTrack.IsPlaying then
			animationTrack:Play()
		else
			animationTrack:Stop()
		end
		
	if key.KeyCode == Enum.KeyCode.Q then
		tweenService:Create(humanoid ,ti, {CameraOffset = Vector3.new(-1.5,0,0)} ):Play()
			if not AnimationTrack.IsPlaying then
				AnimationTrack:Play()
				else
					AnimationTrack:Stop()
		end
		end
		end
end)

UserInputService.InputEnded:connect(function(key)
	if key.KeyCode == Enum.KeyCode.E or key.KeyCode == Enum.KeyCode.Q then
		tweenService:Create(humanoid ,ti, {CameraOffset = Vector3.new(0,0,0)} ):Play()
		animationTrack:Stop()
		AnimationTrack:Stop()
	end
end)

Add in a print statement for every step of the way and see where it stops

I found a minor issue with the code inside the InputBegan function.

This if statement is nested inside that of the E key, meaning it will only fire if the detected key is both Q and E. I was able to get the code to work by changing the if to elseif and deleting one of the following ends.

UserInputService.InputBegan:Connect(function(key, isTyping)
	if key.KeyCode == Enum.KeyCode.E then
		tweenService:Create(humanoid ,ti, {CameraOffset = Vector3.new(1.5,0,0)} ):Play()
		if not animationTrack.IsPlaying then
			animationTrack:Play()
		else
			animationTrack:Stop()
		end
		
	elseif key.KeyCode == Enum.KeyCode.Q then
		tweenService:Create(humanoid ,ti, {CameraOffset = Vector3.new(-1.5,0,0)} ):Play()
			if not AnimationTrack.IsPlaying then
				AnimationTrack:Play()
				else
					AnimationTrack:Stop()
		end
		end
end)
1 Like

Thank you so much for the help! I feel really dumb sometimes lol

Yeah, clean code is important. Keeping track of closing functions can make all the difference @pilzerfa

2 Likes