View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# XNA and loops

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1tharealjohn  Members

Posted 22 June 2012 - 06:37 PM

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,

jmillerdev.com

### #2mhagain  Members

Posted 22 June 2012 - 06:47 PM

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.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.

### #3tharealjohn  Members

Posted 22 June 2012 - 07:27 PM

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?

jmillerdev.com

### #4laztrezort  Members

Posted 23 June 2012 - 12:45 AM

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).

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.