Search code examples
unity-game-enginequaternionsspherical-coordinate

Check if the camera is focused on a sprite


I am writing a Cardboard game in Unity and I want to check whether my camera is facing a sprite or not. I have written the following code:

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

In my code I find the 4 angles of my sprite, which is a square, so I have 5 points which make a pyramid. Now I need to check whether my camera is inside my pyramid or not.

The problem is, my lookTetta and lookFi never goes inside my pyramid. I just checked the Tetta only.

Please help me with it.


Solution

  • I have used IntersectRay using the code below:

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