I'm making a little arcade shooter for 2 players, and need to have the screen focused on 2 players, I got the camera moving in the center of the players in the X axis, but it I think it would be cool when the 2 players get closer together the camera also get closer.
This is the perspective pov:
Moving the camera is better than changing the fov. The formula for calculating the camera distance is
cameraDistance = (distanceBetweenPlayers / 2 / aspectRatio) / Tan(fieldOfView / 2);
Note the players appear on the very edge of the viewport thus some small margin could be added. Here is my script again:
public Transform player1;
public Transform player2;
private const float DISTANCE_MARGIN = 1.0f;
private Vector3 middlePoint;
private float distanceFromMiddlePoint;
private float distanceBetweenPlayers;
private float cameraDistance;
private float aspectRatio;
private float fov;
private float tanFov;
void Start() {
aspectRatio = Screen.width / Screen.height;
tanFov = Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView / 2.0f);
}
void Update () {
// Position the camera in the center.
Vector3 newCameraPos = Camera.main.transform.position;
newCameraPos.x = middlePoint.x;
Camera.main.transform.position = newCameraPos;
// Find the middle point between players.
Vector3 vectorBetweenPlayers = player2.position - player1.position;
middlePoint = player1.position + 0.5f * vectorBetweenPlayers;
// Calculate the new distance.
distanceBetweenPlayers = vectorBetweenPlayers.magnitude;
cameraDistance = (distanceBetweenPlayers / 2.0f / aspectRatio) / tanFov;
// Set camera to new position.
Vector3 dir = (Camera.main.transform.position - middlePoint).normalized;
Camera.main.transform.position = middlePoint + dir * (cameraDistance + DISTANCE_MARGIN);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With