Detection Perimiter

What is the best way to detect an enemy that enters a radius of a turret?

background info.

  • there is no way of telling who the enemy will be, only that they will be an enemy.
  • the turret should have two radius’s, one for ground units, the other for air.
  • the air radius will have to be larger.
  • I will need to cast a ray from the gun to the target to check for obstructions.

Any help will be greatly appreciated.

Use a trigger: child to the turret an invisible object with a capsule collider (uncheck the Mesh Renderer component to make it invisible), adjust it’s radius and height to the volume you want to detect and set Is Trigger, then in the OnTriggerStay compare the tag to learn if it’s an enemy. If it is, cast a ray to its direction to check if the object is visible:

function OnTriggerStay(col: Collider){
  if (col.tag == "enemy"){
    if (Physics.Raycast(transform.position, col.transform.position-transform.position, detectionRadius){
      // enemy at sight: do whatever you want
    }
  }
}

If the air radius must be much larger than the land radius, repeat the trick: use another trigger to detect it, but ignore the enemy if its position.y is below some height.

and as for the Air Targets and Ground Targets simply have a set range for Air like 100-300 it can hit Air and below 100 it can only target ground which would simply just be the guns second distance check 0-100.
I have a some code somewhere if you like to see an example of how to target something at a distance.

Actually the best way would be to create an array of gameojects and find the closest one to the turret then assign the target to the closest I have a video where I have a turret that fires at closest target:
Youtube : Multi-Targetting Turret - YouTube