c# – 始终在播放器前显示对象

我一直困在这个简单的问题,但无法理解为什么我无法控制它.

我有这些代码行在播放器的某个旋转处在我的播放器前面显示我的画布对象(代码中的camRotationToWatch对象名称).

if (camRotationToWatch.transform.localEulerAngles.x >= navigationCanvasXMinmumLimit && camRotationToWatch.transform.localEulerAngles.x <= navigationCanvasXMaximumLimit)
        {
            if (!navCanvasHasDisplay) 
            {

                navigationCanvas.SetActive(true);
                //Debug.Log(camRotationToWatch.transform.forward);
                Vector3 navCanvas = camRotationToWatch.transform.position + camRotationToWatch.transform.forward * navCanvasDisplayDistanceFromCam;
                navCanvas = new Vector3(navCanvas.x, 2f, navCanvas.z);
                navigationCanvas.transform.position = new Vector3(navCanvas.x, navCanvas.y, navCanvas.z);

                navigationCanvas.transform.rotation = camRotationToWatch.transform.rotation;

                navCanvasHasDisplay = true;

            }
        }

        else
        {
            //navigationCanvas.SetActive(false);
            if (locationPanel.activeSelf == false && infoPanel.activeSelf == false) {
                navigationCanvas.SetActive(false);
                navCanvasHasDisplay = false;
            }
        }

当camRotationToWatch对象从向下旋转到向上并且Canvas显示在正确位置时,此代码实际上工作正常但是当我尝试将camRotationToWatch从上到下旋转时,它显示(活动)Canvas在最顶部位置.如何限制画布显示在相同位置(无论播放器从上到下旋转还是向下旋转),但显示在播放器对象的前面?

最佳答案 有点难以弄清楚你想要做什么.但这就是我认为你想做的事情

public GameObject follow; // The object you want to rotate around
public float distance = 2; // Distance to keep from object

private void Update() {
    Vector3 forward = follow.transform.forward;
    forward.y = 0; // This will result in Vector3.Zero if looking straight up or down. Carefull

    transform.position = follow.transform.position + forward * distance;
    transform.rotation = Quaternion.LookRotation(forward, Vector3.up);
}

我相信你的“意外行为”是由于使用欧拉角,因为它们并不总是完全可预测的.尽可能尝试使用Quaternions或Vector3.Angle().

如果要限制角度(例如……如果向下或向上俯视超过45°禁用对象),您可以执行以下操作:

if (Vector3.Angle(forward, follow.transform.forward) > maxAngle) { ... }
点赞