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

前端 未结 5 428
我在风中等你
我在风中等你 2020-12-29 00:11

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

5条回答
  •  时光取名叫无心
    2020-12-29 01:14

    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);
    }
    

提交回复
热议问题