c# - Error upon spawning multiple boundingBoxes "System.ArgumentOutOfRangeException" -
i'm trying create boundingboxes
(collision) between enemy , bullets it's struck with. unfortunately, i'm beingness presented error system.argumentoutofrangeexception
every time enemy leaves screen, or more 1 bullet spawned @ time.
both bounding boxes created in update
functions of bullet & enemy classes such:
boundingbox = new rectangle((int)position.x, (int)position.y, texture.width, texture.height);
this relevant code beingness used in game1
update function:
for (int = bullets.count - 1; >= 0; i--) { bullets[i].update(gametime); error occurs here -> if (bullets[i].boundingbox.intersects(enemies[i].boundingbox)) { score += 1; bullets.removeat(i); } //bullets beingness destroyed upon leaving if (bullets[i].position.y < 0) bullets.removeat(i); }
any help appreciated.
also, here how implemented bullet list game1
class if helps @ all?:
list<bullet> bullets = new list<bullet>(); public void shoot (vector2 pos, vector2 dir, float speed) { bullet bullet = new bullet(bullettexture); bullet.position = pos; bullet.direction = dir; bullet.speed = speed; if (bullets.count() < 40) //maximum amount of bullets bullets.add(bullet); }
if have guess, error comes if (bullets[i].boundingbox.intersects(enemies[i].boundingbox))
statement.
basically, have same amount of enemies , bullets time? if not, fail whenever numbers different.
why this? well, using 2 different collections, bullets
, enemies
, , taking element @ position i
.
so if have 5 bullets 1 enemy in collection, first iteration of have i = 4
, position not exist in enemies
collection (it has enemies[0]
position).
one way solve problem be:
foreach (enemy in enemies) foreach (bullet in bullets) if (bullet.boundingbox.intersects(enemy.boundingbox)) { // logic here. }
you go through every enemy, , each 1 check if bullet intersecting it. not best solution performance wise, think it's start.
c# monogame
No comments:
Post a Comment