Remember that adventure game engine I posted about? Remember
how it attaches instances of Monster to the stage using, then pushes them to the
char array for later reference? I've added new code for when the player attacks. It draws a rectangle named hitBox, positions it according to where the player is and which direction he's facing, then runs a hitTest to see if any Monster instances overlap hitBox. If they do, the game removes them using removeChild(). Here's the new function:
private function attack (attackType) {
if (attackType == "sword") {
var leftEdge:Number = char[0].x - (heroWidth * 0.25) - swordLength;
var rightEdge:Number = char[0].x + (heroWidth * 0.25);
var topEdge:Number = char[0].y - (heroHeight * 0.25) - swordLength;
var bottomEdge:Number = char[0].y + (heroHeight * 0.25);
var vertAlign:Number = char[0].y - (heroHeight * 0.75);
var horizAlign:Number = char[0].x - (heroWidth * 0.5);
//check for monsters and objects
for ( i = 0 ; i < char.length ; i++ ) {
if (i > 0) {
var hitBox:Sprite = new Sprite();
hitBox.graphics.beginFill(0xFF0000);
hitBox.name = "hitBox";
//add hitBox to the left
if (char[0].currentFrameLabel == "swordLeft") {
hitBox.graphics.drawRect(0, 0, swordLength, heroHeight);
addChild(hitBox);
hitBox.x = leftEdge;
hitBox.y = vertAlign;
}
//add hitBox to the right
else if (char[0].currentFrameLabel == "swordRight") {
hitBox.graphics.drawRect(0, 0, swordLength, heroHeight);
addChild(hitBox);
hitBox.x = rightEdge;
hitBox.y = vertAlign;
}
//add hitBox above
else if (char[0].currentFrameLabel == "swordUp") {
hitBox.graphics.drawRect(0, 0, heroWidth , swordLength);
addChild(hitBox);
hitBox.x = horizAlign;
hitBox.y = topEdge;
}
//add hitBox below
else if (char[0].currentFrameLabel == "swordDown") {
hitBox.graphics.drawRect(0, 0, heroWidth , swordLength);
addChild(hitBox);
hitBox.x = horizAlign;
hitBox.y = bottomEdge;
}
if (hitBox.hitTestObject(char[i])) {
removeChild(char[i]);
}
removeChild(hitBox);
}
}
} //end sword
}
Everything works fine, but there's a weird bug: after the monster instance is removed, the area where the monster once was remains unwalkable (the engine ordinarily doesn't allow the player to walk through monsters). I'm guessing that this is because I'm not using removeChild correctly here, but I'm not sure how. Would anyone be kind enough to tell me what I'm doing wrong here?