Furiosa & Drunik
I've been tweaking the AI for a tactical game, trying to make the units smarter without adding extra CPU cost. Think you could spot where it still bites?
Yeah, I can take a look. Usually the slowdown comes from extra loops or branching that the AI does each tick. If you’re recalculating pathfinding for every unit, try caching routes or limiting the update frequency. Also keep an eye on those expensive distance checks—swap them for squared distances or pre‑computed grids. Send me the code and I’ll see where the choke is.
Sure, paste the relevant loop or snippet here, and I’ll see where the extra work is hiding.
Sure, paste the relevant loop or snippet here, and I’ll see where the extra work is hiding.
Sure, drop the loop or snippet here and I’ll spot the hidden slowdown.
Sure thing, here’s a typical loop that can bite the CPU if you’re not careful:
```
for each unit in activeUnits:
for each enemy in nearbyEnemies:
if distance(unit, enemy) < attackRange:
attack(unit, enemy)
else:
path = findPath(unit, enemy)
move(unit, path.nextStep)
```
If you’re recalculating the path every tick and doing full distance checks, that’s a sweet spot for a slowdown. Keep an eye on those nested loops and caching.
The double loop is the killer – you’re walking through every enemy for every unit each tick. If two units share the same enemy, the distance test is repeated twice, and you call `findPath` every time the enemy is out of range. Caching a “nearest enemy” per unit, or moving that lookup out of the inner loop, cuts the work dramatically. Also replace `distance(unit, enemy) < attackRange` with a squared distance check; that removes the sqrt entirely. Lastly, only recalc a path when the target moves or when a significant obstacle appears – not every frame. That will shave most of the latency.