Boat Rotation Issue

I’m currently creating my boat system, it uses both physics and CFrame but the part I’m having trouble with involves the math for finding the angle between two parts for finding the rotation of the boat based on the waves, whenever the boat is rotated as seen below it messes up the calculations somehow and makes it do some weird stuff.

Here’s the code -

        front.CFrame = CFrame.new(front.CFrame.X, frontheight, front.CFrame.Z)
		back.CFrame = CFrame.new(back.CFrame.X, backheight, back.CFrame.Z)
		left.CFrame= CFrame.new(left.CFrame.X, leftheight, left.CFrame.Z)
		right.CFrame = CFrame.new(right.CFrame.X, rightheight, right.CFrame.Z)
		
		local boatY = (right.Position.Y + left.Position.Y + back.Position.Y + front.Position.Y) / 4
		
		local h = frontheight - backheight
		local b = front.CFrame.Z - back.CFrame.Z
		local angle = math.atan(h/b)
		local pitch = -angle 

		local z = rightheight - leftheight
		local x = right.CFrame.Z - left.CFrame.Z
		local angle = math.atan(h/b)
		local roll= -angle 

		local prim = boat.System.Base

		local look = prim.CFrame.LookVector
		look = Vector3.new(look.X, 0, look.Z)

		local cf = CFrame.new(boatpos, boatpos + look)
		cf *= CFrame.fromOrientation(pitch / 3, 0, 0)
		cf *= CFrame.fromOrientation(0, 0, roll / 3)

		Model.System.Rotation:PivotTo(cf)

Here’s the video of the issue -

I hope I included enough information, please ask if you need to know what a certain line is in the code.