In video you see enemies firing rockets at player. I know 2 ways how to make enemies fire rocket only within certain range:
- get vector.distance , it needs to be calculated for every enemy either every (Nth) frame in update or in coroutine
- create trigger collider and switch bool “within range” based on trigger enter and exit
Maybe you have more?
Which one to use and why?
This has been discussed a number of times. The answer is usually that you should do a stress test to check it out and see for yourself, but I think that is common sense that the trigger is less expensive, provided you’re not using super crazy mesh colliders. Specially if you use a layer mask for the trigger, and only check the player’s layer.
I’m not an expert on this, but however they calculate it (I don’t know the function behind and it’s probably not available since Unity is not open source), it should be super easy to just check if the player is within the area of the bounding box.
Let’s just imagine and hiptotethical solution of what they could be doing behind the scenes: let suppouse they first check both objects position in Y, and then subract a maximum radius for both objects (treated as if both had sphere colliders). It’s just a substraction, and it would be very easy to discard the object at any time, and it’ll only had to keep calculating the X component and the details of the collider shape if the first condition would be met, and only after x evaluates also to true, continue, and of course it’lll be less expensive the simpler both colliders are.
The distance is surley a bit more expensive, since I think it uses pythagoras to calculate the diagonal. I bet even if you only run the distance every x frames, the trigger would probably be way more efficient. Maybe they could just get the hypotenuse by applying trigonometry, but probably woud still be more expensive than the collider option in most cases.