- Home /
Controlling Distance with RotateAround
I have an independent camera rotating around a player object with Transform.RotateAround based on the mouseX and mouseY.
What's the best way (without parenting camera to player - code only), to make sure the camera always repositions itself a certain distance behind the player, based on that angle?
Here's what I was trying but it leaves my camera frozen behind the player. Any thoughts?
`function LateUpdate () {
//CAMERA INPUT
this.transform.RotateAround(target.transform.position, Vector3.up, baseLookSpeed * Input.GetAxis("Mouse X")); //mouse x input
this.transform.RotateAround(target.transform.position, Vector3.right, baseLookSpeed * Input.GetAxis("Mouse Y")); //mouse Y input
//rotate player to match.
target.transform.eulerAngles.y = this.transform.eulerAngles.y; //rotate player to match camera angle.
//POSITION CAMERA
var newCamPosition:Vector3 = target.transform.position + (Vector3.back * distToPlayer); //this line freezes cam behind player.
this.transform.position = newCamPosition;
//rotate & angle camera
transform.LookAt(target.transform); //look at the player.
Answer by robertbu · Aug 18, 2014 at 09:59 PM
You can do this in a number of different ways, but the simplest might be to change line 12 to:
var newCamPosition:Vector3 = target.transform.position - (target.transform.forward * distToPlayer);
Thank you! That definitely helps, but the problem is that it locks up my vertical camera movement and only moves along the horizontal axis. Is there a way to get it to do both x and y? Look LR as well as UD?
The easiest way to solve the problem you outline is to use two game objects. $$anonymous$$ake an empty game object that has the script above. $$anonymous$$ake the camera a child. Put the code on the camera that does up/down rotation. It is possible to rewrite the above without the two game-object solution if the up/down rotation has limits. If you want me to take a look, show me the code you are using for up/down rotation.
I've made a version before with parent/child relationship between player and camera that works. For this I just wanted one where they remain independent of each other on the hierarchy.
The up/down camera input I'm using is in the code example above if you want to take a look. You may need to scroll right to see the mouse input as a param of the Translate.RotateAround.
I'm actually really close to getting it working after the line 12 change you recommended. Just trying to figure out why it's not also updating the UD as well as the LR ?