检查相机是否专注于精灵

时间:2016-12-11 17:56:46

标签: unity3d quaternions spherical-coordinate

我正在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。

请帮帮我。

2 个答案:

答案 0 :(得分:1)

使用WorldToViewportPoint它应该是一个单一的声明。无需手动处理查看锥体。

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

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

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

答案 1 :(得分:0)

我使用下面的代码使用IntersectRay

public bool IsLookingAtMe(Vector3 origin, Vector3 direction)
{       
    Bounds bounds = GetComponent<Renderer>().bounds;        
    Ray ray = new Ray(origin, direction);
    return bounds.IntersectRay(ray);
}