x


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?

more ▼

asked Sep 17 '10 at 09:40 AM

KrazyKain gravatar image

KrazyKain
6 3 3 9

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Sep 17 '10 at 09:52 AM

jashan gravatar image

jashan
10.1k 25 40 116

Sir, I think I love you :)

hehe thanks man, it worked perfectly, couldnt beleive the command was so simple

Sep 17 '10 at 11:02 AM KrazyKain
(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Sep 17 '10 at 10:54 AM

Bampf gravatar image

Bampf
5k 8 19 49

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3013
x960
x64

asked: Sep 17 '10 at 09:40 AM

Seen: 2467 times

Last Updated: Sep 17 '10 at 10:55 AM