Help with rotating a part while remaining attached to another part?

I am designing a building game and I would like to include a part that can rotate a specified amount of degrees without falling apart from were its welded from. but I seem to have trouble with this.

below is an example of what Im trying to accomplish:

before
image

after
image

the red part rotates along the yellow part, and the green part follows the red part as expected, however the red part and yellow part is anchored. all parts are expected to be unanchored and when I attempt to do so the parts fall off of each other.

because these parts would be saved and loaded later only things created by a script can be used. here is the current script I am using:

wait(3)

local mode = Enum.JointCreationMode.All


local connectedpart

local ray = Ray.new(script.Parent.Position,script.Parent.CFrame.LookVector * -5)
local part = workspace:FindPartOnRay(ray,script.Parent)
if part then
	local stuff = {}
	table.insert(stuff,script.Parent)
	workspace:JoinToOutsiders(stuff,mode)
	
	script.Parent:BreakJoints()
	local newweld = Instance.new("WeldConstraint")
	newweld.Parent = script.Parent
	newweld.Part0 = script.Parent
	newweld.Part1 = part
	table.insert(stuff,part)
	script.Parent.CFrame = script.Parent.CFrame * CFrame.Angles(math.rad(40),0,0)
	workspace:JoinToOutsiders(stuff,mode)
	
	
end

something to note, by removing the weld constraint, normal welds do not take over and the part falls and this is also a problem as the whole thing is supposed to happen again.