How can i center the camera to a moving object using space?

Hello there, I’ve been trying to create a MOBA kind of game (like DOTA, LoL etc) and I want to create a camera that when you push space it centers to your character (and if you do not release space it continues to center to your character even if it moves). So i tried this code in the Update function:

var myplaya:GameObject;
myplaya = GameObject.Find("MyPlayer");
 
if(Input.GetKey(KeyCode.Space)){
    	transform.position.x = myplaya.transform.position.x;
    	transform.position.z = myplaya.transform.position.z; 
    	transform.position.y = 91f; // this is always static i just have it there for when i impliment zoom

it works like I want the only problem is it does center to the character, it centers to another place in the map (however if o move the caracter it moves the same way).

I think I have to add the angle of the camera (x rotation of the camera gameobject) to the equation but i cant figure out how.

Any help?

The most straightforward, flexible solution is creating a camera rig. Create a gameobject at the world origin. Make your camera a child of that gameobject. Reposition the camera to achieve the distance / angle / focus you want. Your code should move the camera’s parent. This allows you to have whatever camera angle / orientation you want while maintaining simple movement logic.