- Home /
Question by
Uuh294 · Jun 25, 2019 at 12:36 PM ·
scripting beginnercamera follow
Camera rotating for rotating object
I want to rotate the camera with respect to a rotating object. I do not want the camera to be a child of an object, but I want to track it using only a script. However, the camera is not connected to the rotation of the object and does not move properly. How do I fix the script?`public class CameraController : MonoBehaviour {
public GameObject player;
private Vector3 offsetPosition;
private float offsetDistance;
void Start()
{
offsetPosition = transform.position - player.transform.position;
offsetDistance = Mathf.Sqrt((Mathf.Pow(offsetPosition.x, 2.0f) + Mathf.Pow(offsetPosition.y, 2.0f) + Mathf.Pow(offsetPosition.z, 2.0f)));
}
void LateUpdate()
{
transform.position = new Vector3(player.transform.position.x + offsetDistance * Mathf.Sin(player.transform.rotation.y - Mathf.PI),
player.transform.position.y + offsetDistance * Mathf.Sin(player.transform.rotation.x - Mathf.PI),
player.transform.position.z + offsetDistance * Mathf.Cos(player.transform.rotation.x - Mathf.PI));
transform.rotation = player.transform.rotation;
}
}`
Comment
Your answer