How to rotate the camera around an object

I want the camera to rotate around a ball, while the ball can move up and down and such. So like if the ball were to take a turn, then the camera would turn around with it. My code was:
public class CameraController : MonoBehaviour
{

    public GameObject player;

    private Vector3 offset;

    public float rotateSpeed = 3.0F;
    void Start()
    {
        offset = transform.position - player.transform.position;
    }
    void LateUpdate ()
    {
        transform.position = player.transform.position + offset;
        transform.Rotate(0, Input.GetAxis("Horizontal"), 0);

    }
}

What do you actually want? Do you want camera to just repeat the balls rotations so it will always rotate around the ball while the ball will be rotated around its axes? In this case, if the ball is controlled by physics, it will give you a crazy camera that will spin around the ball while the ball is spinning along the ground/terrain.


Or maybe you control the ball rotation manually and you want the camera to follow the ball rotations?

In this case you’ll need to do the following:

You’ll need to update the offset in Update(). Because if you set the offset just in the Start() method, the vector will be pointing out at the same direction in world coordinates system as it has been pointing at the Start(). And using the same vector as an offset, you actually tell the camera not to turn around the ball.

Also, you need to make the offset dependent on the ball rotation. So, when the ball rotates, the offset vector would point out from the ball in some direction relative to the ball current rotation.

For example, you’ll need to preset the desired distance between the camera and the ball (e.g., offsetDistance = 2f ) and use the transform’s forward property which represents the transform’s current forward direction (the direction the object is looking at).

void Update() {
    Vector3 positionForCamera = player.transform.position - player.transform.forward * offsetDistance;
}

This will give you a position that will always stay behind the player/ball’s back on the desired distance. And when the player/ball will rotate, its forward vector will change too, therefore the positionForCamera will change too, because it depends on the player/ball’s forward direction vector.

UPDATE (forgot about rotation):

And then you need to rotate the camera to look at the ball:

void LateUpdate() {
    //set camera position
    transform.position = positionForCamera;
    //set camera rotation
    transform.rotation = Quaternion.LookRotation(player.transform.position - transform.position, Vector3.up);
}

if you want camera to follow ball just make the camera child of ball gameobject and it will move and rotate with it.