• Advertisement
Sign in to follow this  

Unity How to manage multiple enemies/mobs in open world RPG

This topic is 878 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there gamedev community,

 

I'll go directly to the question.

How is the best way to handle A LOT of enemies without slowing my game process?.

I am currently testing, i have a vector of an "enemy" class, and its fine for my testing purposes. The problem is, imagine i have +3000 enemies in my map, how can i manage to execute their IA Behavior, and test who the player attacked, etc.

Im currently using a for loop from 0 to MAX_ENEMIES_IN_GAME, but with +3000 enemies my fps will drop to almost zero hahaha.

Sorry for my bad english, i'll re-write the question if needed, just ask!

Thanks

for (int j = 0; j< MOBS_EN_JUEGO; j++)
	{
		_mobs[j].run(_pj.getX(),_pj.getY(),&_pj); //Make the enemy walk to player position
	}

EDIT: I thought something like, only test the enemies who are close to the player, but for selecting those enemies, i would have to do the same for loop, so... haha.

The only way i can think of it, its to make a bunch of 100x100 areas instead of a full map, so i can forget about the enemies that are not in the area

Edited by Azokasion

Share this post


Link to post
Share on other sites
Advertisement

 

for() loops aren't slow. The logic they contain can be slow. Iterating over 100,000 objects shouldn't be a problem. If 3000 is slowing you down, it's the code within the for() loop. Could you post your run() function?

  • Are you re-doing the pathfinding every tick? You should only be doing the pathfinding when the environment changes, and just cache the result.
     
  • Are you doing complicated AI decision-making for every entity every tick? Try doing it every N tick. i.e. if you have 3000 entities, do 0-1000 AI logic one tick, 1000-2000 the next tick, and 2000-3000 the third tick. You still have every entity update/move every frame, but they only "rethink" every few frames.
     
  • As you mentioned, the farther away an entity is, the less frequently it should think. If an entity is 500 feet away, offscreen, maybe make it only think once every ten ticks. If it's really far away, don't update it at all if your game design permits it.
     
  • My guess is your real slowdown is that you're accidentally drawing all the entities even when they are off-screen. I doubt the code you posted is the real slowdown (unless it's actually doing pathfinding in the run() function). Have you actually profiled yet? Profiling tells you where your program is spending the most time.

 

Thank you for the answer.

Actually, i dont implemented all that enemies yet, i was only trying to get a picture of some programming tricks for the case, so i dont really know if my game will slow down that much.
You gave me some nice ways to do it in case my design needs it, thank you, i would never came with the second one haha.

As for the drawing, i coded a camera system that ensures im only drawing only what i can see.
 

Share this post


Link to post
Share on other sites
Run a profiler on your game. Find out _for sure_ where the slowdown is.

If you're on Windows, use Very Sleepy as a free profiler. There's also a profiler built into Visual Studio.

If you're on Linux, consider perf, which is a very capable tool (though not the easiest to use because, you know... Linux).

Share this post


Link to post
Share on other sites

The problem is, imagine i have +3000 enemies in my map, how can i manage to execute their IA Behavior, and test who the player attacked, etc.

Here are some tips with pseudo code:

1. Have a next update/next ai time like this:

obj::updateAi() 
{
   // do something with obj

   
   if(is_player_around==true) {
     // hi-frequent update time
     obj.next_ai_updattime = current_time + 100;
   } else {
     // low-frequent update time
     obj.next_ai_updattime = current_time + 3000;
   }
}


main_loop:
for each obj in my_game_objects do
{
   if(obj.next_ai_updatetime<current_time) {
     obj.updateAI();
   }
}


2. use timed events, e.g. like this

addEvent(event) 
{
   obj.event_list.add(event);
   obj.next_event_time = min(event.execute_at,obj.next_event_time);
}
process_all_events_up_to_time(obj,time)
{
  min_event_time = MAX;
  for each event in obj.event_list do
  {
     if(event.execute_at<current_time) {
       event.execute(obj);
       obj.event_list.remove(event);
     } else {
        min_event_time = min(min_event_time,event.execute_at);
     }
  }
  obj.next_event_time = min_event_time;

}

main loop:
for each obj in my_game_objs do
{
   if(obj.next_event_time<current_time) {

      process_all_events_up_to_time(obj,current_time);
   }
}

3. for objects, which needs to be updated really seldomly, e.g. a pusling shrine which is active for only a few seconds after being triggered, use the event system instead of the update system like this:

pulsing_shrine_triggered_update(obj) = 
{

   // do something, e.g. heal nearby creatures

   // done ?
   if(!done) {
     // trigger again in 1 second
      obj.addEvent(pulsing_shrine_triggered_update,current_time+1000);
   }
}




4. if you use the tips from above, replicate the times in an array for faster memory access,because you really need to test only the timestamps most of the time. No need to access large objects all the time. Thought the performance benefit might be small to tiny ;-)

Edited by Ashaman73

Share this post


Link to post
Share on other sites
(again, profile first, but...)

You can also use "AI Level of Detail." Enemies that are far away from the camera don't need to update as often because the player can't see them well or at all. They also don't need to have high-fidelity AI.

Reduce the frequency of AI ticks for an enemy based on distance and direction from the view frustrum. Far-away enemies don't need to be all that smart to look believable. Enemies that aren't even near the frustrum can't be seen at all and aren't likely to be seen soon, so they can be really dumb.

Also consider just simplify expensive calculations for those enemies. If the player can't actually see an enemy, there's no point to do high-fidelity path-finding. If the enemy is far enough away they can even just teleport around with nobody being the wiser. The same goes for any other expensive calculations. Friendly inter-NPC interactions can be disabled and inter-NPC combat can be simplified to basic rolls instead of the full combat system.

And of course, if the enemies are really far away, they can just be put on ice and stop updating entirely, or update very very infrequently.

Share this post


Link to post
Share on other sites


Actually, i dont implemented all that enemies yet, i was only trying to get a picture of some programming tricks for the case, so i dont really know if my game will slow down that much.

 

sounds like the thing to do is a rapid prototype of 3000 enemies, and un-optimized AI. IE step one should be to see if brute force is good enough, or whether you have to "get jiggy with it".

 

if it turns out that a vector of 3000 badguys just updating them all isn't fast enough, reach for the profiler. it may indicate a need for the optimizations as described by Servant, Sean, and Ashaman.

 

then you can build the game knowing your already tested system will perform well.

 

always test brute force first.  often it can be good enough. this is an approach i learned from Carmack and Abrams.

 

if brute force won't cut it, then its time for fancy algorithms.

Share this post


Link to post
Share on other sites

Depending on how large your map is you can split the map into separate sections or chunks. Each chunk would contain the entities that lay within it's bounds and it would only update/render those entities if the player is in or near the chunk.

Share this post


Link to post
Share on other sites

in caveman, i was having problems with lots of active targets and AI and accelerated time.  in the end, i went with a 128x limit on accelerated time with badguys nearby and full AI. at time acceleration above 128x with no badguys, i simply model the results of running the non-badguy AI (IE everything eventually wanders off and gets removed from the simulation) , but don't actually run the AI at all. 

 

 

 

and of course if all else fails , you can always have the AI cheat. <g>.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By Manuel Berger
      Hello fellow devs!
      Once again I started working on an 2D adventure game and right now I'm doing the character-movement/animation. I'm not a big math guy and I was happy about my solution, but soon I realized that it's flawed.
      My player has 5 walking-animations, mirrored for the left side: up, upright, right, downright, down. With the atan2 function I get the angle between player and destination. To get an index from 0 to 4, I divide PI by 5 and see how many times it goes into the player-destination angle.

      In Pseudo-Code:
      angle = atan2(destination.x - player.x, destination.y - player.y) //swapped y and x to get mirrored angle around the y axis
      index = (int) (angle / (PI / 5));
      PlayAnimation(index); //0 = up, 1 = up_right, 2 = right, 3 = down_right, 4 = down

      Besides the fact that when angle is equal to PI it produces an index of 5, this works like a charm. Or at least I thought so at first. When I tested it, I realized that the up and down animation is playing more often than the others, which is pretty logical, since they have double the angle.

      What I'm trying to achieve is something like this, but with equal angles, so that up and down has the same range as all other directions.

      I can't get my head around it. Any suggestions? Is the whole approach doomed?

      Thank you in advance for any input!
       
    • By devbyskc
      Hi Everyone,
      Like most here, I'm a newbie but have been dabbling with game development for a few years. I am currently working full-time overseas and learning the craft in my spare time. It's been a long but highly rewarding adventure. Much of my time has been spent working through tutorials. In all of them, as well as my own attempts at development, I used the audio files supplied by the tutorial author, or obtained from one of the numerous sites online. I am working solo, and will be for a while, so I don't want to get too wrapped up with any one skill set. Regarding audio, the files I've found and used are good for what I was doing at the time. However I would now like to try my hand at customizing the audio more. My game engine of choice is Unity and it has an audio mixer built in that I have experimented with following their tutorials. I have obtained a great book called Game Audio Development with Unity 5.x that I am working through. Half way through the book it introduces using FMOD to supplement the Unity Audio Mixer. Later in the book, the author introduces Reaper (a very popular DAW) as an external program to compose and mix music to be integrated with Unity. I did some research on DAWs and quickly became overwhelmed. Much of what I found was geared toward professional sound engineers and sound designers. I am in no way trying or even thinking about getting to that level. All I want to be able to do is take a music file, and tweak it some to get the sound I want for my game. I've played with Audacity as well, but it didn't seem to fit the bill. So that is why I am looking at a better quality DAW. Since being solo, I am also under a budget contraint. So of all the DAW software out there, I am considering Reaper or Presonus Studio One due to their pricing. My question is, is investing the time to learn about using a DAW to tweak a sound file worth it? Are there any solo developers currently using a DAW as part of their overall workflow? If so, which one? I've also come across Fabric which is a Unity plug-in that enhances the built-in audio mixer. Would that be a better alternative?
      I know this is long, and maybe I haven't communicated well in trying to be brief. But any advice from the gurus/vets would be greatly appreciated. I've leaned so much and had a lot of fun in the process. BTW, I am also a senior citizen (I cut my programming teeth back using punch cards and Structured Basic when it first came out). If anyone needs more clarification of what I am trying to accomplish please let me know.  Thanks in advance for any assistance/advice.
    • By Yosef BenSadon
      Hi , I was considering this start up http://adshir.com/, for investment and i would like a little bit of feedback on what the developers community think about the technology.
      So far what they have is a demo that runs in real time on a Tablet at over 60FPS, it runs locally on the  integrated GPU of the i7 . They have a 20 000 triangles  dinosaur that looks impressive,  better than anything i saw on a mobile device, with reflections and shadows looking very close to what they would look in the real world. They achieved this thanks to a  new algorithm of a rendering technique called Path tracing/Ray tracing, that  is very demanding and so far it is done mostly for static images.
      From what i checked around there is no real option for real time ray tracing (60 FPS on consumer devices). There was imagination technologies that were supposed to release a chip that supports real time ray tracing, but i did not found they had a product in the market or even if the technology is finished as their last demo  i found was with a PC.  The other one is OTOY with their brigade engine that is still not released and if i understand well is more a cloud solution than in hardware solution .
      Would there  be a sizable  interest in the developers community in having such a product as a plug-in for existing game engines?  How important  is Ray tracing to the  future of high end real time graphics?
    • By bryandalo
      Good day,

      I just wanted to share our casual game that is available for android.

      Description: Fight your way from the ravenous plant monster for survival through flips. The rules are simple, drag and release your phone screen. Improve your skills and show it to your friends with the games quirky ranks. Select an array of characters using the orb you acquire throughout the game.

      Download: https://play.google.com/store/apps/details?id=com.HellmodeGames.FlipEscape&hl=en
       
      Trailer: 
       
    • By khawk
      Watch the latest from Unity.
       
  • Advertisement