Ann
Ann

Reputation: 79

UNITY3D How check direction vector of my camera?

I'm new in Unity. I've got game with FPS mode, camera rotate with mouse's moves and sun is the directional light. I must write script where I check if sun is in player's field of view. I thought that I can calculate angle between 2 vectors and then I decide if sun is visible. First vector is:

var playerSun =  light.transform.position - camera.transform.position;

But I have problem with the second one... I don't know which variable I should use, camera.transform.forward is ALWAYS (0,0,1)...

Can you help me? I'll be very grateful.

Upvotes: 1

Views: 1363

Answers (2)

Synthetic One
Synthetic One

Reputation: 405

There are several ways to achieve that, but I suggest usage of Raycast. I suppose sun is more than just a dot, it has some area visible to the player, so even if he does not see sun` center point, he still can see some part of its area. If so, I recommend to add a new script to sun object just to identify it programmatically. Then make sure that it has collider component attached with the size approximately equal to sun. Then in your script in which you want to detect sun visibility to the player you can do something like that:

var ray = Camera.main.ScreenPointToRay(pos);    
RaycastHit hit;

        if (!Physics.Raycast(ray, out hit, 100))
            return false; //sun or any other collider wasnt hit

        var objHit = hit.collider.gameObject.GetComponent<Sun>();

So objHit != null means that player can see any part of area that sun has.

Upvotes: 1

Everts
Everts

Reputation: 10701

Vector3 direction = light.position - player.position;
float dot = Vector3.Dot(direction.normalized, player.forward);
if(dot > 0) { Debug.Log("Sun is on the front"); }

dot product returns 1 when two vectors are aligned, 0 when they are 90 degrees and -1 when they are opposite.

The value is in radians so if you need a 90 degrees FOV, it would be 45 degrees (since 90 is 45 left and right) and that is appr. 0.7f.

if(dot > 0.7f) { Debug.Log("Sun is withing 90 degrees");}

Upvotes: 3

Related Questions