2012-08-15 111 views
0

本質上,我試圖創建一個遊戲,玩家必須躲避某些物品,到目前爲止,我有一段隨機將3個鯊魚添加到舞臺上的代碼。在for循環中創建多個變量的碰撞檢測?

這個想法是,一旦玩家擊中鯊魚他/她返回到開始位置,我有一個動作腳本文件,其中包含鯊魚的速度,速度等,每當程序運行鯊魚將出現在不同的位置。但是,當我試圖對鯊魚進行碰撞測試時,只有其中一個鯊魚作出反應,我無法弄清楚如何讓所有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 
} 

}

回答

0

只需將用於循環到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; 
     } 
    } 

} 

你不能只經過了一次循環,並設置currentShark變量 - 你會就這樣結束每次執行碰撞測試時都要對一個鯊魚進行測試。相反,每次你想檢查碰撞時,你都必須循環所有的鯊魚並進行碰撞測試。

+0

非常感謝!不知道爲什麼我沒有想到,現在看起來如此明顯!感謝您的快速響應;) – dMo 2012-08-15 14:40:07