Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep 2 objects in view at all time by scaling the field of view? (or z&y axis)

Tags:

c#

unity3d

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:

like image 313
stepper Avatar asked Nov 29 '22 11:11

stepper


1 Answers

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);
}
like image 140
jparimaa Avatar answered Dec 04 '22 21:12

jparimaa