--------------------------------------------------------------------------------------
--------------------[ PRE-CONNECTIONS ]-----------------------------------------------
--------------------------------------------------------------------------------------


local function updateAnimVars()
	wait()
	Forward = (UIS:IsKeyDown("W") or UIS:IsKeyDown("Up"))
	Backward = (UIS:IsKeyDown("S") or UIS:IsKeyDown("Down"))
	local Right = UIS:IsKeyDown("D")
	local Left = UIS:IsKeyDown("A")
	
	local walkingForward = (Forward and (not Backward))
	local walkingBackward = ((not Forward) and Backward)
	local walkingRight = (Right and (not Left))
	local walkingLeft = ((not Right) and Left)
	
	if (Forward or Backward or Right or Left) then
		Walking, Idling = true, false
		if (not Running) and (not Aimed) then
			spreadMotion = "Moving"
			baseSpread = S.spreadSettings[spreadZoom][spreadStance][spreadMotion]
		end
	elseif (not (Forward and Backward and Right and Left)) then
		Walking, Idling = false, true
		if (not Aimed) then
			spreadMotion = "Idling"
			baseSpread = S.spreadSettings[spreadZoom][spreadStance][spreadMotion]
		end
	end
	
	local newArmTilt = (
		((walkingForward or walkingBackward) and walkingRight) and 2.5 or
		((walkingForward or walkingBackward) and walkingLeft) and -2.5 or
		((not (walkingForward and walkingBackward)) and walkingRight) and 5 or
		((not (walkingForward and walkingBackward)) and walkingLeft) and -5 or 0
	)
	local newMoveAng = (
		(walkingForward and (not (walkingRight or walkingLeft))) and 0 or
		(walkingForward and walkingRight) and RAD(-45) or
		((not (walkingForward or walkingBackward)) and walkingRight) and RAD(-90) or
		(walkingBackward and walkingRight) and RAD(-135) or
		(walkingBackward and (not (walkingRight or walkingLeft))) and (moveAng < 0 and RAD(-180) or RAD(180)) or
		(walkingBackward and walkingLeft) and RAD(135) or
		((not (walkingForward or walkingBackward)) and walkingLeft) and RAD(90) or
		(walkingForward and walkingLeft) and RAD(45) or 0
	)
	
	local newAnimCode = math.random(-1e9, 1e9)
	animCode = newAnimCode
	local startTilt = armTilt
	local startAng = (ABS(moveAng) == RAD(180)) and (newMoveAng > 0 and RAD(180) or RAD(-180)) or moveAng
	local Increment = (startTilt == newArmTilt and 1.5 / 0.7 or 1.5 / (0.35 * ABS(startTilt - newArmTilt) / 5))
	local X = 0
	while true do
		RS.RenderStepped:wait()
		local newX = X + Increment
		X = (newX > 90 and 90 or newX)
		if animCode ~= newAnimCode then break end
		armTilt = numLerp(startTilt, newArmTilt, Sine(X))
		moveAng = numLerp(startAng, newMoveAng, Sine(X))
		if X == 90 then break end
	end
end

M2.KeyDown:connect(updateAnimVars)
M2.KeyUp:connect(updateAnimVars)
updateAnimVars()
