- Home /
Cheapest way to get distance detection and triggered events.
Hey guys,
I'm trying to trigger enemy events at certain distances, for instance shooting at the player when he comes within range.
What's the cheapest way to handle this? vector3.Distance seems to munch CPU like there is no tomorrow when you have quite a few objects trying to calculate at the same time. All that square rooting I guess.
For the time being I've resorted to a HUGE (some 150 game units!) sphere collider set as a trigger around the player. Doing a similar thing in reverse for enemies caused big performance issues as well.
I'm sure there must be a nicer and more cost efficient way of handling this, I suspect this is a noob question set to get flamed but I couldn't find any solid reference for it. Is raycasts the way forward?
Thanks in advance!
Answer by Owen-Reynolds · Mar 31, 2011 at 07:05 AM
Set a coroutine that runs only 4 times a second (or whatever) and checks shooting and other AI stuff. If you spawn a lot of enemies at once, give them a random 0-0.25 sec start time, to stagger them. Less AI checking also gives the "free" effect that if you pop out from behind a wall (for example,) they appear to have a slight, random reaction time.
Answer by DaveA · Mar 31, 2011 at 12:29 AM
There's probably a guru answer to this, but you can avoid the square-root by just doing squares and comparing them at that point. No point in doing square-root if you don't really need to.
Thanks man, tried doing sqrmagnitude ins$$anonymous$$d but that still humped the CPU. quite a lot of these bods doing this stuff at once.
You can also go for Ham$$anonymous$$g (or $$anonymous$$anhattan?) distance if it doesn't have to be perfectly circular. Basically max(abs(dx),abs(dy))