update camera position by calculation

i am building my 3d game’s camera and i am trying to script my own camera script.
i have a character and a camera where character is not the parent of the camera.
(i.e. they are separated so that the camera will not follow the character rotation when moving )
alt text

in the image, the center is the character, the cross is the camera and the arrow is the facing of character.

  1. at the beginning, camera is 10 unit behind the character.
  2. camera rotate clock-wisely( or anti clockwise), calculate the distance on x and z for re-positioning.
  3. the character can move freely(360 degree movement) and camera have to following it.

I am really weak in calculating sin cos and fail in calculating the distance, could anyone help on the calculatedistance() function?

public Transform target;  //character's transform
float xdistance = 10;
float zdistance = 0;
function Update(){
    if(Input.GetKey("w")){
        transform.RotateAround(target.position,Vector3.up,-2f);
        this.transform.lookat(target.position);
    }
    if(Input.GetKey("o")){	
        transform.RotateAround(target.position,Vector3.up,2f);
        this.transform.lookat(target.position);
    }


    transform.position.y = target.position.y;
    calculatedistance(target.transform, this.transform);
    transform.position.x = target.position.x - xdistance;
    transform.position.z = target.position.z - zdistance;
 
}

I have built one demo. you try it if it satisfy your requirement.
In empty scene, assign below script to main camera and in that script assign your character.

    public GameObject Charactet;
    private float distanceFromCharacter = 5;

    void Update()
    {
        //move character
        Charactet.transform.Translate(Input.GetAxis("Horizontal") * 5 * Time.deltaTime,0, Input.GetAxis("Vertical") * 5 * Time.deltaTime,Space.Self);

        //rotate character
        Charactet.transform.Rotate(Vector3.up, Input.GetAxis("Mouse X"));

        //camera should be here
        Vector3 targetPoint = Charactet.transform.position - Charactet.transform.forward * distanceFromCharacter;

        transform.position = targetPoint;
        transform.LookAt(Charactet.transform);
    }

If this is not what you want let me know.