I’m trying to create a game involving enemies that spawn from the ceiling and fall onto platforms. From their they walk to the end of their platform and fall, and then turn around, repeating the process. This involves a few for loops (some double), and hitTestPoint tests.
There is about 70 platforms on screen to which each enemy is being collision checked against at all times. I realize this is a lot, but I didn’t think it would be near enough to slow the game down completely.
As a test, my code currently spawns 30 enemies onscreen, which is a lot but isn’t too unrealistic in comparison to what I need. Once at least 3 enemies get on screen, things start to slow down a lot. Especially when an enemy is in freefall (which is weird considering I believe that is when less calculations occur).
I have posted example code, and attached the project itself for more detail.
I keep getting too discouraged when I encounter problems like this and stop my projects… so I hope this is easy to resolve.
public function tick(event:TimerEvent){
var i:int;
for(i=0;i<enemyList.length;i++){
//trace(enemyList*.vy+" "+enemyList*.vx);
enemyList*.vy+=gravity;
if(enemyList*.onGround){
if( Math.floor((enemyList*.y-(enemyList*.height/2)) / gridSize) % 2 == 0) enemyList*.direction=1;
else enemyList*.direction=-1;
enemyList*.walk();
}
else enemyList*.falling();
var collision=enemyCollisionFloor(enemyList*);
if(collision != -1){
//trace(collision);
enemyList*.y = collision;
enemyList*.vy=0;
}
if(enemyList*.vy==0) enemyList*.onGround=true;
else enemyList*.onGround=false;
enemyList*.applyFriction(0.8);
enemyList*.updatePos();
}
}
...
public function enemyCollisionFloor(enemy:Enemy):int{
var i:int;
var p:int;
var r:int;
for(i=0;i<groundList.length;i++){
for(p=1;p<=enemy.vy;p++)
//for(r=0;r<enemy.width;r++)
if(groundList*.hitBox.hitTestPoint(enemy.x+enemy.vx,enemy.y+p,false) ||
groundList*.hitBox.hitTestPoint(enemy.x+(enemy.width/2)+enemy.vx,enemy.y+p,false) ||
groundList*.hitBox.hitTestPoint(enemy.x+(enemy.width)+enemy.vx,enemy.y+p,false)){
//trace("hitbox y: "+(groundList*.y+groundList*.hitBox.y)+" vy: "+vy+" enemy y: "+enemy.y+" collision y: "+(enemy.y+p));
return groundList*.y+groundList*.hitBox.y;
}
}
return -1;
}