How do I stop this tween?

Im trying to make a script where there are 2 CameraParts/Points, if the player holds a key down then it will move to the next CameraPart, if the player stops holding the key down then it will stop moving to the next Camerapart.

local Camera = workspace.CurrentCamera
local Views = workspace:WaitForChild("Views")
local tweenService = game:GetService("TweenService")
local UIS = game:GetService("UserInputService")


function tweenCamera(pos,tweenTime)
	tweenService:Create(Camera,TweenInfo.new(tweenTime,Enum.EasingStyle.Sine), {CFrame = pos.CFrame}):Play()
end

UIS.InputBegan:Connect(function(input)
	if input.KeyCode==Enum.KeyCode.W then
	tweenCamera(Views.ViewRight, 9)
		
	end
	end)

UIS.InputEnded:Connect(function(input)
	if input.KeyCode==Enum.KeyCode.W then
	tweenCamera:Stop()
end
end)

I tried to achieve this using tweenService. It moves, but it wont stop if I stop holding the key down.

Can someone help me with this?

You could try returning the tween like this…

function tweenCamera(pos,tweenTime)
	local result = tweenService:Create(Camera,TweenInfo.new(tweenTime,Enum.EasingStyle.Sine), {CFrame = pos.CFrame})
   return result
end

then when the user input ended instead of stop use pause() which will pause the animation
by doing this u are returning the animation to the inputBegan event/inputEnded
so you could make the tweencamera function a variable which will return the tween in doing this you would be able to control the tween when ever you call the function

local result =  tweenCamera(Views.ViewRight, 9)
UIS.InputBegan:Connect(function(input)
	if input.KeyCode==Enum.KeyCode.W then
	result:Play()	
	end
	end)

UIS.InputEnded:Connect(function(input)
	if input.KeyCode==Enum.KeyCode.W then
	result:Pause()
end
end)
1 Like