Hi All!
I’m looking for best way to find out is player within enemy range attack or not for my 2d Space rescue arcade game (video below).
First, i tried to create script attached to every enemy and used coroutine to calculate distance to player NOT every frame.
It works fine, you may see it on video.
Then I started to figure out is there a better way mostly for rapid fire enemies like laser and plasma cannons
I found this post:
Quote from it here:
If you use the Physics system like you originally thought, you can avoid the distance computations every frame. Add a SphereCollider to your AI. Set the radius to minRange. You could add the collider by hand or automatically within the EnemyAI script. Tick Is Trigger to make it a trigger. Since the AI will presumably move, add a Rigidbody and tick Is Kinematic (unless the AI already has a rigidbody).
Then add OnTriggerEnter and OnTriggerExit methods to keep track of when the player enters the trigger area:
This is not real but close to it code:
Class InRange
Public bool IsInRange = false;
void OnTriggerEnter2d(Collider2d other) {
if (other.tag == “Player”) IsInRange = true;
}
void OnTriggerExit2d(Collider2d other) {
if (other.tag == “Player”) IsInRange = false;
}
I tried it this way:
-
add child game object to main enemy game object inside enemy prefab
-
Add a circle Collider 2d to child object
Set the radius to 100
Tick Is Trigger to make it a trigger.
I have Rigidbody on main game object so i didn’t add one more to child,but I tick Is Kinematic -
add script like quoted above but with 2d triggers
-
modified coroutine in main game object:
- at start - assignment for child component variable pointer to script with triggers above
- at coroutine itself - check InRange.IsInRange boolean instead of calculating distance.
Good thing: triggers work as expected. IsInRange getting true or false.
Bad thing: game become extremely slow (1 fps!)in scene where I tried these new enemies with triggers.
Why? What is wrong?
I will post real code here soon