- Home /
Activate object only if camera views it
In my top scrolling space shooter I'm giving every enemy some sort of script intelligence, but I obviously only want this AI to kick in when they are within view of the camera. Now it is possible to add a timer variable which counts down and then manually alter it to match the rate at which the camera will reach the enemy, but that feels very inefficient. Is there a good way to get a boolean that turns true as soon as the camera sees the object?
Answer by jashan · Sep 17, 2010 at 09:52 AM
You're looking for Renderer.isVisible
if (renderer.isVisible) {
DoSomeComplexEffect();
}
What you'd probably do is: In every update (or every few updates, could be also controlled via a Coroutine), check whether the state of renderer.isVisible has changed (went from false to true, or vice versa). When the object became visible, start your AI.
Or, you could have your AI code in the if:
if (renderer.isVisible) {
HandleAIStuff();
}
Depends much on how your AI is exactly implemented.
There's one thing to be aware of, though: isVisible will also be true if the shadow of the object is visible (which sometimes is the case even though you wouldn't expect it). So watch out with this, if you're using shadows.
Oh, and of course: any camera (including scene view cameras in the editor). So that also requires be a little careful when testing this.
Sir, I think I love you :)
hehe thanks man, it worked perfectly, couldnt beleive the command was so simple
Answer by Bampf · Sep 17, 2010 at 10:54 AM
Other good answers to this question can be found here. In particular, if you have multiple cameras you can use OnWillRenderObject instead.
Another way not mentioned is to use raycasting. That would be the way to go if you want to account for obstacles blocking the view of the camera/enemy. Here is an answer on that topic.
Answer by bliztertoto · Dec 18, 2013 at 06:36 PM
If you want to do it without any renderer:
Calculate the vector between your camera and your object then Dot your camera.transform.forward with the difference vector. If they are in the same direction, then the object is in front of the camera.
Then using WorldPointToScreenPoint, make sure the object is within the viewport rect.
Your answer
Follow this Question
Related Questions
How to change camera visibility after certain distance? 0 Answers
Can't see a flare from above? 0 Answers
light sound sensitive AI 1 Answer
How to check that a game object is shown on screen? 0 Answers