Tweening Rotating models with heartbeat service

I am using heartbeatservice to get the position and rotation of the prompt.

I am very confused why ‘rotatecoeff’ 360 is resetting to 0 instead of tweening from 270 to 0 in the shortest way possible, how can I fix this? I had looked at other forums but none provided enough help, this was as far as I could get.

clonedprompt:PivotTo((CFrame.new(raycastResult.Position) * CFrame.new(0,buildheighty,0)) * CFrame.Angles(0,math.rad((rotatecoeff)),0))


Rotatecoeff is tweened when ‘R’ is pressed

local rotatecoeff = 0
local function tweennumber()
	local tweenvalue = Instance.new("NumberValue")
	tweenvalue.Value = rotatecoeff
	tweenvalue.Changed:connect(function()
		rotatecoeff = tweenvalue.Value
	end)
	local tweenInfo = TweenInfo.new(0.2, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
	tweenservice:Create(tweenvalue, tweenInfo, { Value = rotate }):Play()
end

if input.KeyCode == Enum.KeyCode.R then
		rotate = (rotate + 90) % 360
		--print(rotate)
		tweennumber()
end

unknown_2024.10.23-20.51

yeah thats bc wrapping around values like 360 and 0 can lead to issues like jumps or resets especially when tweening.

local tweenservice = game:GetService("TweenService")
local rotatecoeff = 0
local rotate = 0

local function tweennumber(target)
    local tweenvalue = Instance.new("NumberValue")
    tweenvalue.Value = rotatecoeff

    -- this sets up tween to the shortest path
    tweenvalue.Changed:Connect(function()
        rotatecoeff = tweenvalue.Value
    end)

    local tweenInfo = TweenInfo.new(0.2, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut)
    local shortestRotate = (target - rotatecoeff + 540) % 360 - 180
    local newTarget = rotatecoeff + shortestRotate

    tweenservice:Create(tweenvalue, tweenInfo, { Value = newTarget }):Play()
end

if input.KeyCode == Enum.KeyCode.R then
    rotate = (rotate + 90) % 360
    tweennumber(rotate)
end

oh and i also forgot to mention some things, so instead of directly tweening to target you need to calculate newTarget based on the shortest direction from the current rotatecoeff.