C# -> Index was out of range error | Using Lists -
C# -> Index was out of range error | Using Lists -
i using xna create tank game. i've implemented feature shoot bullets using list. after shooting, want test if bullet has gotten close boundaries of screen. if so, remove particular bullet list.
the error appears when have more 1 bullet on screen @ given time. here code:
tank class:
list<bullet> bulletlist = new list<bullet>(); bool spacebarprepared = true; //for shooting every 0.5 seconds short count = 0; //shoot if (keyboard.getstate().iskeydown(keys.space) && spacebarprepared == true) { bulletlist.add(new bullet(sprbullet, position, turretdirection, turretangle)); spacebarprepared = false; } if (spacebarprepared == false) { spacebarcount += (float)gametime.elapsedgametime.totalseconds; if (spacebarcount > 0.5) { spacebarprepared = true; spacebarcount = 0; } } //update bullets foreach (bullet bullet in bulletlist) { bullet.update(bounds); } count = (short)bulletlist.count; //remove unwanted bullets (short = 0; < count; i++) { if (bulletlist[i].alive == false) { bulletlist.remove(bulletlist[i]); } }
bullet class:
class bullet { texture2d spr; vector2 origin, pos, dir, turretlength; float rotation, scale, turretleng; short speed; bool live = true; public bullet(texture2d sprite, vector2 position, vector2 direction, float angle) { spr = sprite; scale = 0.15f; turretleng = (110 + spr.width) * scale; speed = 5; rotation = angle; pos = position; dir = direction; origin = new vector2(spr.width / 2, spr.height / 2); findturretlength(); } public void draw(spritebatch spritebatch) { matrix bullettranslation = matrix.createrotationz(rotation) * matrix.createtranslation(pos.x + turretlength.x, pos.y + turretlength.y, 0); spritebatch.begin(spritesortmode.backtofront, null, null, null, null, null, bullettranslation); spritebatch.draw(spr, vector2.zero, null, color.white, 0, origin, 0.15f, spriteeffects.none, 1f); spritebatch.end(); } public void update(vector2 boundary) { pos += dir * speed; if (pos.x < 50 || pos.x > boundary.x - 50 || pos.y < 50 || pos.y > boundary.y - 50) { live = false; } } public void findturretlength() { turretlength = new vector2(turretleng * dir.x, turretleng * dir.y); } public vector2 pos { { homecoming pos; } set { pos = value; } } public bool live { { homecoming alive; } set { live = value; } } }
what noticed myself when debugging own 'count' variable = 2, yet bulletlist.count = 1. problem? how occurring?
any help appreciated.
the problem in loop removes bullets.
lets have list of 10 bullets (indexes 0 - 9) when start loop. 1st bullet (at index 0) gets removed....now list has 9 bullets (indexes 0 - 8), count variable has not been updated loop still thinks has 10.
when reach point "i" greater actual amount of bullets alive, you'll "index out of range." error.
there multiple ways can prepare error.
i go for:
bulletlist.removeall(x => !x.alive);
c# list count xna
Comments
Post a Comment