I'm working on a sorta football game where I need my player to always be at the center of the camera view while keeping the ball into view, without any vertical movement. The idea would be for the camera to act like the picture below.
What I came up with was the following code that I'm using in a LateUpdate. I'm computing a directional vector between the player and the ball and placing my camera behind the player using that data, and then I look at my player.
Vector3 ballPosition = ballTransform.position; Vector3 playerPosition = playerTransform.position; ballPosition.y = 0.0f; playerPosition.y = 0.0f; Vector3 directionVector = (ballPosition - playerPosition).normalized; directionVector.y = 0.0f; Vector3 newPosition = playerTransform.position - directionVector * 12.0f; newPosition.y = 9.0f; transform.position = newPosition; transform.LookAt(playerTransform.position);
The code itself is working, but the camera movement is a bit nauseous, and when I'm trying to smooth it I end up with the ball leaving the camera field most of the time. Plus when I get too close from the ball I end up with some really quick camera movements which makes the whole thing kinda hard to follow. I tried to use a totally different technique by working with a Cinemachine Camera, but there doesn't seem to be an easy way to achieve such a view.
Does anyone have an idea of how to achieve such a thing?