johnny 5 johnny 5 - 5 months ago 47
C# Question

Unity Camera Maintain perspective while rotating

I'm trying to write a camera script which will maintain the perspective point which I'm looking at while rotating.

public void RegisterRotationControls()
var horizontal = CrossPlatformInputManager.GetAxis(InputAxisName.Horizontal.ToString());

offsetX = Quaternion.AngleAxis(horizontal * turnSpeed, Vector3.up) * offsetX;
transform.position = player.position + offsetX;

transform.LookAt(player.position + PlayerOffset);

Currently this script is only working properly when the camera is looking at the player, however the camera has freedom to move position yet the rotation should maintain relativity to the center. enter image description here

The top row dipicts the current behavior, while the bottom depicts what should be occuring


Manually calculating the rotation to move a camera in a circle while retaining its original (relative) facing is somewhat cumbersome, and requires you to do a lot more math than you need to.

A popular solution is to parent the camera under an empty GameObject, and centering that GameObject on the point/object you want the camera to rotate around. (This basically internalizes a lot of the calculations, letting the engine do the heavy lifting.) Then, you can locally translate the camera as needed and then rotate the container GameObject to move the camera in a circle.