I have added a few instances of a movieclip (a simple image of an apple) on to the stage at random x and y. Now I am trying to click on each one to remove them.
Here is what I have:
public function Apples() {
for(var count:int=1; count<=10; count++){
var apple = new Apple();
apple.x = Math.random() * stage.stageWidth;
apple.y = Math.random() * stage.stageHeight;
apple.name = count;
stage.addChild(apple);
}
stage.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void{
stage.removeChild(e.target);
}
}
I get the following error if I try to compile:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.display:DisplayObject.
I have also tried substituting e.target.name for e.target. In this case the program runs, but as soon as I click on the apple, I get the following error in the output log:
TypeError: Error #1034: Type Coercion failed: cannot convert "9" to flash.display.DisplayObject.
at MethodInfo-4()
So is there any way to remove the specific object that I am clicking on?
In your onClick event handler try something like:
var displayObject:DisplayObject = (DisplayObject) (e.target);
displayObject.parent.removeChild(displayObject);
You may also want to make sure the event handler is added to the display object using a weak reference, if it is meant to be completely gone/removed on click.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.