You are here: JGT Tutorial >
7. Killing enemies
Lesson 3: Killing, and Being Killed
Let's start with the fun stuff :)
Killing enemies
Our program already has almost all the necessary things for us to kill enemies. The only thing that's needed is to check collisions between the bullets and the enemies. There's a class in the JGT just for that, it's called CollisionDetection. Let's use it in the main loop to detect collisions.
while (_gameRunning) {
(...)
Pair<List<VisibleObject>> collision;
collision =CollisionDetection.findCollisionListSlow(_bullets,_enemies);
if (null!=collision) {
for (VisibleObject bullet : collision._a) {
bullet._alive = false;
}
for (VisibleObject enemy : collision._b) {
enemy._alive=false;
}
}
}
CollisionDetection takes two lists of objects that extend Rectangle, and return a Pair. That Pair has two elements: _a is a list of bullets (in our case) and _b is a list of enemies. The first bullet in _a collides with the first enemy in _b, and so on. One particularity of CollisionDetection is that if there's no collision it may return null instead of a Pair of emtpy lists. You can see that the code tests for this case.
The code here marks all collided objects as "not alive". Bullets already have code to be removed from the game when they're not alive but we need to add it to the enemies. The old code is below.
for (Enemy e : _enemies) {
e.move();
}
We replace it with the following code, very similar to the code for the bullets:
for (Iterator<Enemy> ei = _enemies.iterator(); ei.hasNext();) {
Enemy e = ei.next();
e.move();
if (!(e._alive)) ei.remove();
}
Now, bullets hit enemies and make them disappear.
Next: 8