Rotating object around another object in godot issue...

so I have a basic setup whereby box B seeks out box A and then box B rotates around box A. I’ve made a simple state machine for box B . however, when playing the scene , at whatever angle I place box B at as a starting point , when it transitions from state SEEK to state ROTATE, theres a momentary moment where it looks like a frame is skipped . However, I gathered that the point at which the rotation begins is a fixed point. How do I manipulate it so that whichever angle box B comes at towards box A it will transition at the angle set by box B ? . below is the script for box B:

extends KinematicBody

export var r = 1
var theta = 0
var dtheta = 2 * PI / 250
var rotationLimit = PI # Set the limit to half a circle
var boxA
var boxB
var stopping_distance = 1.0
var velocity = Vector3.ZERO
var move_speed = 3.0

var state = states.IDLE

enum states {
IDLE
SEEK
ROTATE
}

func _ready():
boxA = get_node(“…/boxA”)
boxB = get_node(“…/boxB”)

func _process(delta):
rotateAround()

func rotateAround():
match state:
states.IDLE:
var direction_to_player = get_node(“…/boxA”).global_transform.origin - global_transform.origin
var distance_to_player = direction_to_player.length()
if distance_to_player < stopping_distance:
velocity = Vector3.ZERO
else:
state = states.SEEK

	states.SEEK:
		var direction_to_player = boxA.global_transform.origin - global_transform.origin
		var distance_to_player = direction_to_player.length()
		direction_to_player = direction_to_player.normalized()
		
		if distance_to_player > stopping_distance:
			velocity = direction_to_player * move_speed
			move_and_slide(velocity)
		elif distance_to_player < stopping_distance:
			state = states.ROTATE
	
	states.ROTATE:
		theta += dtheta

		if theta <= rotationLimit:
			var cosTheta = cos(theta)
			var sinTheta = sin(theta)

			boxB.transform.origin.x = boxA.global_transform.origin.x + r * cosTheta
			boxB.transform.origin.z = boxA.global_transform.origin.z + r * sinTheta
			boxB.transform.origin.y = boxA.global_transform.origin.y
		else:
			theta = rotationLimit  # Stop the rotation at the limit
			state = states.IDLE

your theta value always starts at zero. I think you should calculate the point/angle at which the box enters the rotation circle. The range will be 0 to 2 pi. I think the dot product is what you need to find the angle of the difference vector. Or maybe angle_to