为Unity3D构建正交相机,如何保持四个特定目标在视线范围内

本文关键字:四个 目标 范围内 视线 构建 Unity3D 相机 何保持 | 更新日期: 2023-09-27 18:29:51

我有一台2D正交相机,用于一款与网球类似的游戏。我一直在为此编写代码,我想到目前为止我只是其中的一部分。此刻。。。它…有点让两个玩家保持在同一帧中,帧更多地指向人类玩家——玩家一。然而,它也有下降到地面以下的趋势,尤其是当它缩小以保持目标在视野中时。有四个特定目标:地面、球、球员一和球员二。

地面应该总是在"底部",否则当相机进入地面时,它会显示天空——这并不是一个理想的效果。这是我迄今为止开发的代码。。。这两名选手实际上是划桨手,但它只显示了他们之间的中心:

using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
    // Moving Camera, This Camera tries to follow Player One, Two, and Ball //
public static CameraController Instance;
public Transform PlayerOne;
public Transform PlayerTwo;
public Transform Ball;
public bool Ready = false;
private float MinX = -46.0f;
private float MaxX = 46.0f;
private float MinY = 12.0f;
private float MaxY = 35.0f;
private float LimitFromPlayerX = 20.0f;
private float LimitFromPlayery = 20.0f;
private float DistanceToGround = 0.0f;
private float DistanceFromCenter = 2.0f;
private float Height = 4.0f;
private float Damping = 5f;
private Vector3 EstimatedCameraPosition = Vector3.zero;
private Vector3 WantedPosition = Vector3.zero;
void Awake()
{
    Instance = this;
}
public void SetCameraPosition()
{
    Vector3 PlayerPosistion = PlayerOne.position;
    PlayerPosistion.z = -10.10f;
    transform.position = PlayerPosistion;
}
// Update is called once per frame
void FixedUpdate () {
    if (Ready) {
        Vector3 PlayerPosistion = PlayerOne.position;
        PlayerPosistion.z = -10.10f;
        Vector3 CameraPosition = transform.position;
        CameraPosition.z = -10.10f;
        // Get the Distance from the Player to the Ball //
        Vector3 WantedPosition = PlayerTwo.transform.position - -PlayerOne.transform.position;
        float WPMag = Mathf.Abs(WantedPosition.magnitude);
        WPMag = Mathf.Clamp(WPMag, 20, 40);
        Debug.Log(WPMag);
        Camera.main.orthographicSize = WPMag;
        transform.position = Vector3.Lerp(CameraPosition, WantedPosition, Damping * Time.deltaTime);
    }
}
void LateUpdate()
{
    Vector3 Posit = transform.position;
    Posit.x = Mathf.Clamp (Posit.x, MinX, MaxX);
    Posit.y = Mathf.Clamp (Posit.y, MinY, MaxY);
    transform.position = Posit;
}

}

WPMag是我的尝试,至少缩小并匹配玩家,但到目前为止,它只是部分起作用。

为Unity3D构建正交相机,如何保持四个特定目标在视线范围内

要保持所有三个对象都在视图中,您需要将相机聚焦在三个对象的中点或"平均"位置。获取三个对象的中点就像获取两个对象的中间点一样:(PlayerOne.position + PlayerTwo.position + Ball.position) / 3.0f

然后,您需要将正交大小设置为距离三个被跟踪对象中点的最远距离。这将确保所有三个对象都保持在帧中。

最后,为了防止相机显示地下天空,您应该强制设置相机Y位置的下限。正交大小是视口垂直高度的一半,因此应使用CameraPosition.y = Mathf.Max(CameraPosition.y, groundHeight + camera.main.orthographicSize)