Search Unity

Unit AI Patterns

Discussion in 'Entity Component System' started by dthurn, Oct 18, 2019.

  1. dthurn

    dthurn

    Joined:
    Feb 17, 2015
    Posts:
    77
    I'm doing an RTS-type thing, and I'm currently looking at patterns to implement simple types of unit AI using DOTS. I've been specifically wondering a lot about responding to the position of other entities. For example, consider the case of the AI for a defensive Turret building which needs to fire on the closest opposing unit that comes within range. The dumb way to implement this is basically to have a loop every frame like this:

    Code (CSharp):
    1. foreach (turret in turrets) {
    2.   var closestUnitDistance = int.MaxValue;
    3.   foreach (unit in units) {
    4.     var distance = Distance(unit, turret);
    5.     if (distance < turret.Range && distance < closestUnitDistance ) {
    6.       turretTarget = unit;
    7.       closestUnitDistance = distance;
    8.     }
    9.   }
    10. }
    This is obviously a pretty inefficient algorithm to running every frame, though. Is there a better way to structure this kind of algorithm in an ECS world?
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Unity Physics would generally be a decent approach to limit the number potential targets.
     
  3. Kmiecis

    Kmiecis

    Joined:
    Oct 11, 2017
    Posts:
    12
    What? Why? It is pretty straightforward and the math is pretty lightweight, especially with burst here.
    Yeah, you can try other approaches like creating grid and make units update their grid position before searching for them, using physics as mentioned or maybe make units talk to turrets about their changed position. Also there is option to slow down a bit by updating every few frames. But all those add unnecessary and possibly slower code. Simple math is simple.
     
  4. paul-figiel

    paul-figiel

    Joined:
    Feb 9, 2017
    Posts:
    9
    You should definitely try Unity Physics, it's not that convoluted and really easy to use. I don't know what kind of algorithm they are running, probably a spatial hashmap or a quadtree of some sort, but it's for sure better than the "dumb" way.

    I'm currently developing a tower defense game and I manage to have 5 000 turrets aiming at the closest of 5 000 targets with really good performance using Unity Physics. And I haven't tried to optimize in any way for now.
     
  5. schaefsky

    schaefsky

    Joined:
    Aug 11, 2013
    Posts:
    90
    Any more specific examples on how to use Unity Physics for that? (Sorry, I am new to game programming / Unity in general)
     
    MNNoxMortem likes this.