Issues With Flipping Character Model Upside Down

Hello! I am trying to make a system where when the player presses “E”, they get completley flipped upside down. So the gravity, their character, and their camera. Everything works except the player model flips between a state of being upside down and not being upside down.


image

local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local CharacterFlipped = false
local Camera = workspace.CurrentCamera 
local renderSteppedConn

local function invertGravityAndFlip()
	local character = Players.LocalPlayer.Character
	if character and character:FindFirstChild("Humanoid") then
		local humanoid = character.Humanoid
		print("Inverted Gravity")
		if not CharacterFlipped then
			-- Flip character upside down
			local rootPart = character:FindFirstChild("HumanoidRootPart")
			if rootPart then
				game.Workspace.Gravity = -300
				renderSteppedConn = RunService.RenderStepped:Connect(function()
					Camera.CFrame *= CFrame.Angles(0, 0, math.rad(180))
					rootPart.CFrame = rootPart.CFrame * CFrame.Angles(math.rad(180), 0, 0)
				end)
				CharacterFlipped = true
			end
		end
	end
end

local function restoreGravityAndOrientation()
	local character = Players.LocalPlayer.Character
	if character and character:FindFirstChild("Humanoid") then
		local humanoid = character.Humanoid
		print("Restored Gravity")
		-- Restore original orientation
		local rootPart = character:FindFirstChild("HumanoidRootPart")
		if rootPart and CharacterFlipped then
			game.Workspace.Gravity = -196
			if renderSteppedConn then
				renderSteppedConn:Disconnect()
			end
			rootPart.CFrame = CFrame.new(rootPart.Position) -- Resets the CFrame to initial position
			CharacterFlipped = false
		end
	end
end

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.E then
		if Players.LocalPlayer.Character and Players.LocalPlayer.Character:FindFirstChild("Humanoid") then
			if not CharacterFlipped then
				print("E key pressed")
				invertGravityAndFlip()
			else
				print("Triggerd")
				restoreGravityAndOrientation()
			end
		end
	end
end)

I’m not sure how to prevent it from doing this loop. All help is apreciated!

You’re constantly changing the rootparts CFrame by 180 on the y axis every renderstepped. Try moving rootPart.CFrame = rootPart.CFrame * CFrame.Angles(math.rad(180), 0, 0) outside the renderstepped event