0

我正在 Unity 中编写 Cardboard 游戏,我想检查我的相机是否面向精灵。我写了以下代码:

private void GetSphericalCoordinates(Vector3 vector, out float tetta, out float fi)
{
    float r = Mathf.Sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);
    tetta = Mathf.Acos(vector.z / r);
    fi = Mathf.Atan2(vector.y, vector.x);
}

public bool IsLookingAtMe(Vector3 point, Quaternion angle)
{
    Vector3 topLeftPoint = new Vector3(transform.position.x - transform.localScale.x / 2, transform.position.y - transform.localScale.y / 2);
    Vector3 topRightPoint = new Vector3(transform.position.x + transform.localScale.x / 2, transform.position.y - transform.localScale.y / 2);
    Vector3 bottomLeftPoint = new Vector3(transform.position.x - transform.localScale.x / 2, transform.position.y + transform.localScale.y / 2);
    Vector3 bottomRightPoint = new Vector3(transform.position.x + transform.localScale.x / 2, transform.position.y + transform.localScale.y / 2);        

    float topLeftTetta, topRightTetta, bottomLeftTetta, bottomRightTetta, lookTetta;
    float topLeftFi, topRightFi, bottomLeftFi, bottomRightFi, lookFi;
    GetSphericalCoordinates(topLeftPoint - point, out topLeftTetta, out topLeftFi);
    GetSphericalCoordinates(topRightPoint - point, out topRightTetta, out topRightFi);
    GetSphericalCoordinates(bottomLeftPoint - point, out bottomLeftTetta, out bottomLeftFi);
    GetSphericalCoordinates(bottomRightPoint - point, out bottomRightTetta, out bottomRightFi);
    lookTetta = angle.eulerAngles.x * Mathf.Deg2Rad;
    lookFi = angle.eulerAngles.y * Mathf.Deg2Rad;


    if (lookTetta >= topLeftTetta && lookTetta <= bottomRightTetta)
        return true;
    return false;
}

在我的代码中,我找到了我的精灵的 4 个角度,这是一个正方形,所以我有 5 个点构成一个金字塔。现在我需要检查我的相机是否在我的金字塔内。

问题是,我的lookTetta 和lookFi 永远不会进入我的金字塔。我只检查了Tetta。

请帮帮我。

4

2 回答 2

1

使用WorldToViewportPoint它应该是一个单一的语句。无需手动处理视锥。

将精灵世界位置投影到视口位置,然后查找它是否在边界内(忽略 z)。

public bool IsMainCameraLookingAtMe()
{
  Bounds viewportBounds = new Bounds.SetMinMax(Vector2.zero, Vector2.one);
  return viewportBounds.Contains((Vector2)Camera.main.WorldToViewportPoint(transform.position));
}

可以单独检查每个精灵角以满足您的需要。

于 2016-12-12T07:00:24.313 回答
0

IntersectRay使用过以下代码:

public bool IsLookingAtMe(Vector3 origin, Vector3 direction)
{       
    Bounds bounds = GetComponent<Renderer>().bounds;        
    Ray ray = new Ray(origin, direction);
    return bounds.IntersectRay(ray);
}
于 2016-12-12T14:08:19.563 回答