- Home /
OnBecameVisible - question
This is my current code:
function OnBecameVisible() {
Debug.Log("Object Seeennnn!");
}
function OnBecameInvisible() {
Debug.Log("Object vision lost");
}
I want to debug when the camera, or actually the player sees the object this script is attached to.
However, this OnBecameVisible function triggers when the object is in the camera's field of view, regardless of the objects with renderers inbetween. It just looks through them.
I'm keeping in mind that this function triggers all camera's in the scene.
I'm quite lost here and I'd like help to achieve what I'm trying to achieve, and that is: detect if the player/camera actually SEES the object instead of it being in the viewport.
Thanks in advance guys! :)
I'm keeping in $$anonymous$$d that this function triggers all camera's in the scene.
For giggles, try turning off / removing all the other cameras besides main camera and see if the issue continues? I just plugged your code into what I'm working on and it seems to work.
Also, this is a silly question but something similar happened to me yesterday :P : what is this script attached to in your code?
It's attached to the object I want to check if seen. In this case a cube for testing purposes. The thing I'm trying to achieve is to check if object is seen, then when the player turns around, the scary character appears and then dissappears. Horror type game :) !
Answer by whydoidoit · Apr 12, 2013 at 09:19 PM
So you can't do that with a frustum test - you need to check whether you can see it by raycasting from the camera towards the object - you only need to bother doing that when the object is being rendered by the camera.
function OnBecameVisible()
{
StartCoroutine("CheckForVisible");
}
function OnBecameInvisible()
{
StopCoroutine("CheckForVisible");
}
function CheckForVisible()
{
var mainCamera = Camera.main.transform;
while(true)
{
var direction = (transform.position - mainCamera.position);
var distance = direction.magnitude;
if(!Physics.Raycast(mainCamera.position, direction, distance - 0.4)) //Or some other factor
{
SendMessage("Seen");
return;
}
yield WaitForSeconds(0.2);
}
}
This will call the Seen method on other scripts on the same game object when it is seen by the main camera.
Wow, thanks a lot! :) It totally worked except for the yield break part. It kept giving errors. I figured to delete the 'break' and make it yield;. However, this resulted in the function debugging/calling the 'seen' every 0.2 secs. Despite that, amazing work. Thanks! I can figure the rest out (:
Ugh - yield break is C# damn it - :S Ok - you could try just to "return" or StopCoroutine("CheckForVisible");
Haha yea I was wonderin bout it :). Anyways, sure I can, didnt know I had to. Thanks a bunch.