1
我遇到的問題基本上是,我在舞臺上實例化了'Target'對象五次。發生這種情況,但只有一個對象能夠在其上執行hitTestPoint。任何人都可以幫助爲什麼發生這種情況?ActionScript多個對象實例化hitTestPoint
下面是代碼:
修訂
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.text.*;
public class TheGameItself extends Sprite {
public var main_class:TheGame;
private var crosshair:Crosshair = new Crosshair;
private var targets:Array = new Array();
public function TheGameItself(passed_class:TheGame) {
main_class = passed_class;
addTargets(4);
Mouse.hide();
addChild(crosshair);
crosshair.x = mouseX;
crosshair.y = mouseY;
addEventListener(MouseEvent.MOUSE_MOVE, moveCrosshair);
}
private function addTargets(numOfTargets:int):void {
for (var i:int = 0; i < numOfTargets; ++i) {
targets[i] = new Target;
targets[i].x = 100 * i + 70;
targets[i].y = 100;
targets[i].scaleX = targets[i].scaleY = .7;
addChild(targets[i]);
addEventListener(MouseEvent.CLICK, collisionDetection);
}
}
private function collisionDetection(e:MouseEvent):void {
targets.forEach(detectCollision);
}
private function detectCollision(element:*, index:int, targets:Array):void {
if (element.hitTestPoint(mouseX, mouseY, true) && targets.length > 0) {
trace("["+index+"]"+" "+element);
collisionNotification.text = "Yes";
} else {
collisionNotification.text = "No";
}
}
public function moveCrosshair(e:MouseEvent):void {
crosshair.x = mouseX;
crosshair.y = mouseY;
}
}
}
感謝您的幫助 - 但它似乎沒有工作。我瞭解您的示例中發生了什麼,但問題依然存在。只有一個對象是鼠標點擊的,其餘的則沒有反應。 – davo0105 2011-05-20 17:04:28
我的猜測是,你只是添加一個事件來處理所有的目標,正確的方法是在循環中的每個目標添加一個事件。我編輯我以前的代碼,看看我標記爲// **更新** – nelsond8 2011-05-21 09:56:46
這些是我對這個問題的初步想法,我只在第一個對象上聽到hitTestPoint事件,而不是全部。我試過你的更新解決方案,但無濟於事。 我已經實現了您的原始解決方案,並將其添加到試圖解決我的問題。我已經更新了原始問題中的代碼。看看它,看看你的想法。 – davo0105 2011-05-22 11:59:41