- Home /
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?
Answer by AlwaysSunny · Aug 28, 2014 at 03:21 AM
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.
Hey!! thnx for the answer!!
I tried your advice and it kinda works.
The problem now is that the camera rotates when my gameobject rotates. What I mean is that the camera now always focuses to one site of my gameobject no matter if i move it up or down and this way you can see the map from a total new side everytime you move (it is not locked from left to right, it goes everywhere). If you have played League of Legends you can understand what i mean (pressing space will center the camera to your champion and if you click to go down the champion goes down and you can see his face or something, if you click up you see his back etc). $$anonymous$$y code at the first post almost did the trick but it just didnt focus at the right place (the camera movement was great however).
Hope I didnt confuse you :P
Are you making the camera rig a child of the player? That's not the intended usage of a camera rig. A typical camera rig should either share or seek the position of the VIP your camera wants to view. In this case, the player.
Its child - which is the actual camera - can have any behavior you like, including no behavior whatsoever, which sounds like what you want. Just means you shouldn't include any code which affects the rotation of the camera or camera rig, and the camera rig shouldn't be a child of anything which can move or rotate.