CFrame.Angle speeds up every time I use it

Hello.

Essentially what I am trying to do is create a system where players can pick up and drag certain parts around the game, whilst being able to rotate them with a held-down key press while the part is being dragged.

To do this, I am using CFrame.Angles, and it works fine, but only for the first time the key is press. Every subsequent press seems to make the part rotate at an increased speed, until it is almost rotating faster than you can see it. I want it to be a constant speed.

local player = game.Players.LocalPlayer 
local mouse = player:GetMouse() 
local target 
local down 

local UserInputService = game:GetService("UserInputService")

keydownR = false
keydownT = false

mouse.Button1Down:connect(function() 
	if mouse.Target ~= nil and mouse.Target.Locked == false then 
		mouse.TargetFilter = target 
	end 
end)

mouse.Move:Connect(function()
	if down == true and target ~= nil then 
		target.Position = mouse.Hit.Position 
	end 
end) 

mouse.Button1Up:connect(function()
	down = false 
	mouse.TargetFilter = nil 
	target = nil
end)

UserInputService.InputBegan:Connect(function(input)
	
	if input.KeyCode == Enum.KeyCode.R then
		if down == true and target~= nil then
			keydownR = true
			while true do
				if keydownR == true then
					
					local oriY = target.Orientation.Y
					
					target.Orientation = Vector3.new(0,(oriY+5),0)
					
				end
				wait()
			end
		end
		
	end
	if input.KeyCode == Enum.KeyCode.T then
		if down == true and target~= nil then
			if down == true and target~= nil then
				keydownT = true
				while true do
					if keydownT == true then
						
						target.CFrame = target.CFrame * CFrame.Angles(math.rad(5), 0, 0)
						
					end
					wait()
				end
			end
		end

	end
end)

UserInputService.InputEnded:Connect(function(input)
	
	if input.KeyCode == Enum.KeyCode.R and keydownR == true then

		keydownR = false
		

	end
	
	if input.KeyCode == Enum.KeyCode.T and keydownT == true then

		keydownT = false
		

	end

end)

I tried using the Orientation property as well, but it seems to do the same thing. It starts out with the first press slow, then every time I release and press again it’s slightly faster. I want the speed to be 5 degrees for every wait() the while loop runs.

Not sure why it does this.

You are running a while loop and never breaking out of it in your InputBegan event. This will make another loop run each time that you press the button. First time input begins, one while loop runs. The second time you input something, two while loops will. You will add another while loop each time you begin some input.
Instead, make keydownR true when input begins, and keydownR false when input ends.
Then, outside all events, on the bottom of the script, put your while loop:

while true do
    if keydownR then
        --stuff
    end
end
1 Like

Yup, that was it. Thank you very much friend.

1 Like