0

本质上,我正在尝试创建一个游戏,玩家必须躲避某些物品,到目前为止,我有一段代码可以将 3 条鲨鱼随机添加到舞台上。

这个想法是,一旦玩家击中了一条鲨鱼,他/她就会返回到起始位置,我有一个包含鲨鱼的速度、速度等的动作脚本文件,每次运行程序时,鲨鱼都会出现在不同的位置。

但是,当我尝试对鲨鱼进行碰撞测试时,只有一条鲨鱼有反应,我无法弄清楚如何让所有 3 条鲨鱼都影响玩家(square_mc)。任何帮助将不胜感激。

//Pirate game, where you have to avoid particular object and get to the finish line to move onto the final level.

stage.addEventListener(KeyboardEvent.KEY_DOWN, moveMode ); 
function moveMode(e:KeyboardEvent):void {

//movements for the pirate ship, this will allow the ship to move up,down,left and right.

if (e.keyCode == Keyboard.RIGHT) {
    trace("right"); 
square_mc.x = square_mc.x + 25;
} 
else if (e.keyCode == Keyboard.LEFT) {
    trace("left"); 
square_mc.x = square_mc.x - 25;
} 
else if (e.keyCode == Keyboard.UP) {
    trace("up"); 
square_mc.y = square_mc.y - 25;
} 
else if (e.keyCode == Keyboard.DOWN) {
    trace("down");
square_mc.y = square_mc.y + 25;
}
}   

//for.fla
//this program uses a for loop to create my Sharks
//a second for loop displays the property values of the sharks

function DisplayShark():void{
for (var i:Number=0;i<3;i++)
{
    var shark:Shark = new Shark(500);
    addChild(shark);

    shark.name=("shark"+i);
    shark.x=450*Math.random();
    shark.y=350*Math.random();

}
}
DisplayShark();

for(var i=0; i<3;i++){
var currentShark:DisplayObject=getChildByName("shark"+i);

trace(currentShark.name+"has an x position of"+currentShark.x+"and a y position  of"+currentShark.y);
}



//here we will look for colliosion detection between the two move clips.

addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void { 

if (square_mc.hitTestObject(currentShark))
{ 
trace("The Square has hit the circle");
    square_mc.x=50
    square_mc.y=50  //these lines of code return the square back to it's     original location
}

}

4

1 回答 1

0

只需将您的 for 循环移动到 ENTER_FRAME:

addEventListener(Event.ENTER_FRAME, checkForCollision);
function checkForCollision(e:Event):void { 

    for(var i=0; i<3;i++){    
        var currentShark:DisplayObject=getChildByName("shark"+i);
        if (square_mc.hitTestObject(currentShark))
        { 
            trace("The Square has hit the circle");
            square_mc.x=50;
            square_mc.y=50;
        }
    }

}

您不能只通过一次 for 循环并设置 currentShark 变量 - 每次执行碰撞测试时,您最终都会针对一只鲨鱼进行测试。相反,每次要检查碰撞时,都必须遍历所有鲨鱼并进行碰撞测试。

于 2012-08-15T14:34:22.717 回答