Game Development Reference
In-Depth Information
Luckily, there is a solution to this problem: iterative testing.
Essentially, we want to test the space between a Sprite
s new posi-
tion and its previous position to see if a collision had occurred
'
In our shooter example, if the distance traveled
between the frame cycles is less than the width of either the pro-
jectile or enemy rects, then our current test is sufficient. However,
once their speed exceeds their width, both Sprites need to iterate
over their traveled distance to determine if they collided with any-
thing in the dead space. This is where using rectangles for the tests
are particularly helpful because you can use a loop to move them
at a certain interval and perform checks each time. Here
between frames.
'
san
example of how you could perform this loop.
for each (var enemy:Enemy in _enemyList) {
if (!enemy.alive) continue;
enemyRect = enemy.getRect(this);
if (enemyRect.width
<
= Math.abs(enemy.speed)) {
"
"
//
CHECK SUFFICIENT
for each (var projectile:Projectile in _projectileList) {
projectileRect = projectile.getRect(this);
if (enemyRect.intersects(projectileRect)) {
removeProjectile(projectile);
enemy.destroy();
LITE
}
}
} else {
var numberOfChecks:int = Math.ceil(Math.abs(enemy.
speed)/enemyRect.width);
for (var i:Number = 0; i < = numberOfChecks; i++) {
var newRect:Rectangle = enemyRect.clone();
newRect.x −= enemyRect.width*i;
for each (var projectile:Projectile in
_projectileList) {
projectileRect = projectile.getRect(this);
if ( newRect .intersects(projectileRect)) {
removeProjectile(projectile);
enemy.destroy();
}
}
}
}
}
In this modified example of the shooter collision check, if the
width of the enemyRect is less than the speed it moved in a single
frame, then the check is performed as usual. However, if the speed
exceeds the width of the rectangle, then we determine how many
checks we need to perform by dividing the speed by the width and