XNA and loops

Started by
2 comments, last by laztrezort 11 years, 10 months ago
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

Follow me @jmillerdev

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.

Direct3D has need of instancing, but we do not. We have plenty of glVertexAttrib calls.

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

Follow me @jmillerdev

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.

This topic is closed to new replies.

Advertisement