I got a small but annoying problem with my Delphi School Project. At school we have to use Delphi 5 (I know, very modern) and to be able to work on it on my own without running into major annoyances, I use Delphi 7 here instead of Lazarus.
I am trying to code a small Space Invaders project with the limited OpenGL knowledge we got taught in our lessons and I am running into the problem when checking the collisions between the bullets the player shoots and the enemies. The Collision Detection Code actually works and counts hits accordingly but when it has to delete the enemy & the bullet from a List (so that they won't be rendered anymore), the List Index Out Of Bounds Error occurs.
procedure TForm1.CheckCollision(enemies, bullets: TObjectList);
var ll, kk: integer;
begin
for ll := Form1.bullets.Count-1 downto 0 do
begin
for kk := Form1.enemies.Count-1 downto 0 do
begin
if TBullet(Form1.bullets[ll]).tby1 >= TEnemy(Form1.enemies[kk]).tey1 then
begin
if TBullet(Form1.bullets[ll]).tbx2 > TEnemy(Form1.enemies[kk]).tex1 then
begin
if TBullet(Form1.bullets[ll]).tbx1 < TEnemy(Form1.enemies[kk]).tex1 + 0.05 then
begin
if TBullet(Form1.bullets[ll]).tby1 <= TEnemy(Form1.enemies[kk]).tey2 then
begin
Form1.enemies.Delete(kk); //error happens here and line below
Form1.bullets.Delete(ll);
inc(score);
end;
end;
end;
end;
end;
end;
end;
This is the code where this error occurs. I do kinda know what this error means but I don't know how to fix it in this instance. The funny thing is, that while in the .exe of this project this error still happens, both the bullet and enemy get deleted and your score gets increased, you just have to quickly press OK after the error message appears and you can continue playing. In Delphi, the program stops after the error obviously.
Hope you guys might be able to help me out here.
Bullet[ll] is deleted in the first kk loop. Hence, in subsequent kk loops, bullet[ll] no longer exists (i.e ll - 1 is "highest" existing index)...