Lerp rotation of 2d gui objects

Hello, I am making a top down shooter game using only gui and am having issues lerping the rotation of turrets without them flipping when they reach one side.

Here is the code for it, I have tried some stuff but I could not get anything to work so I ended up undoing it

local MainUI = script.Parent.Parent.Parent
local Player = MainUI.Player
local Turret = script.Parent.Turret
local Cannon = Turret.Top

local sine = 0

function Lerp(a, b, t)
	return a + (b - a) * t
end

game["Run Service"].RenderStepped:Connect(function()
	sine+=1
	
	Turret.Gear.Rotation=sine*2 -- just for looks
	
	local difference = (Player.AbsolutePosition - Turret.AbsolutePosition)
	local rot = -math.deg(math.atan2(difference.X, difference.Y))
	Turret.Rotation = Lerp(Turret.Rotation,rot,.05) -- rotate with lerp to make it smooth
	
	print(rot)
	print(Turret.Rotation)
end)

If anyone knows of a solution for this I would be very grateful!

That is for position not rotation.

See if this fixes your problem:

local lerpPct = .05
game["Run Service"].RenderStepped:Connect(function()
	sine+=1

	Turret.Gear.Rotation=sine*2 -- just for looks
	
	local difference = (Player.AbsolutePosition - Turret.AbsolutePosition)
	local rot = -math.deg(math.atan2(difference.X, difference.Y))
	if rot < 0 then
		rot += 360
	end
	
	local rotDiff
	
	if rot >= 0 and rot < 90 and Turret.Rotation >= 270 and Turret.Rotation < 360 then
		rotDiff =  (rot+360 - Turret.Rotation) * lerpPct
	elseif Turret.Rotation < 90 and Turret.Rotation >= 0 and rot >= 270 and rot < 360 then
		rotDiff =  (Turret.Rotation+360 - rot) * -lerpPct
	else
		rotDiff = (rot - Turret.Rotation) * lerpPct
	end
		
	Turret.Rotation += rotDiff 
	Turret.Rotation = Turret.Rotation % 360
end)
4 Likes

This works flawlessly!!! I can’t thank you enough :3

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.