• Advertisement
Sign in to follow this  

XNA and loops

This topic is 2038 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

Hello,

I am working on a tower defense game using XNA 4.0.

I have gotten to a point where I am questioning if I am doing things the right way, and if there is a better to do some of what im doing. For the most part, most of my logic seems to be countless foreach or for loops going through lists of enemies or towers, etc and apply some calculations or conditionals on properties.

I feel like the more complex my game will get, the more lists and loops Ill have to add to check each enemy and tower for information. As the lists grow, the game starts to slow down. How can I handle this differently?

Basically my level has a List<Enemy> enemies and a List<Tower> towers.

In an public void Update(GameTime gameTIme) function there are a few foreach loops doing some logic on positions, alive, distance, etc.

Suggestions on how to handle this better?

Thanks,

Share this post


Link to post
Share on other sites
Advertisement
Simplest approach would be to partition your map into regions. Do one loop through your tower list and assign each tower to a region (this can be done just once at startup). Do one loop through your enemy list and assign each enemy to a region (this only needs to be done at startup and when an enemy's position changes). Now you only need to check enemies vs towers when they're in the same region, which can dramatically cut down the exponential overhead when numbers start increasing.

Share this post


Link to post
Share on other sites
Hm, that's an interesting idea. So what you're saying is that if I do something like this, I will just be checking for things in the same region each cycle, rather than everything?

Share this post


Link to post
Share on other sites
I'm suprised you are seeing a slowdown just from looping through game objects (unless you have a lot of objects, or you are doing complex logic on each one, or you are performing too many iterations needlessly).

I suggest you post your Update code, it may help you get some feedback.

Share this post


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

  • Advertisement