ActionScript 3:错误#2025

War*_*ren 0 flash actionscript-3 flash-cs5 flash-cs6

我的代码运行正常.当用户按下1时,假设引入一个图像,当他/她按下2时将其交换为另一个图像.但是,当我在先前按下相同的数字后按1或2时,我得到#2025错误.例如:按1然后再按1.

ArgumentError:错误#2025:提供的DisplayObject必须是调用者的子级.at flash.display :: DisplayObjectContainer/removeChild()at warren_fla :: MainTimeline/reportKeyDown2()

import flash.events.KeyboardEvent;

var bdata = new image1(stage.stageWidth, stage.stageHeight);
var bdata2 = new image2(stage.stageWidth, stage.stageHeight);
var bmp = new Bitmap(bdata);
var bmp2 = new Bitmap(bdata2);

function reportKeyDown(event:KeyboardEvent):void 
{ 
if (event.keyCode == 49) {
    //trace("1 is pressed");
    bmp.x = 230;
    bmp.y = 150;
    addChild(bmp);
}
if (contains(bmp2)) {
    removeChild(bmp2);
    }
}

function reportKeyDown2(event:KeyboardEvent):void 
{ 
if (event.keyCode == 50) {
    //trace("2 is pressed");
    bmp2.x = 230;
    bmp2.y = 150;
    addChild(bmp2);
    removeChild(bmp);
}

} 

stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown2);
Run Code Online (Sandbox Code Playgroud)

Bar*_*klı 6

您正在删除bmp而不检查它是否已经是孩子.

function reportKeyDown2(event:KeyboardEvent):void 
{ 
    if (event.keyCode == 50) {
        //trace("2 is pressed");
        bmp2.x = 230;
        bmp2.y = 150;
        addChild(bmp2);
        if(contains(bmp)) 
            removeChild(bmp);
    }
} 
Run Code Online (Sandbox Code Playgroud)

您的代码也可以重构为这个更简单的版本:

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

var bdata = new image1(stage.stageWidth, stage.stageHeight);
var bdata2 = new image2(stage.stageWidth, stage.stageHeight);
var bmp = new Bitmap(bdata);
var bmp2 = new Bitmap(bdata2);

function reportKeyDown(event:KeyboardEvent):void 
{ 
    if (event.keyCode == Keyboard.NUMBER_1) {
        swapBitmaps(bmp, bmp2);            
    } else if (event.keyCode == Keyboard.NUMBER_2) {
        swapBitmaps(bmp2, bmp);            
    }
}

function swapBitmaps(first:Bitmap, second:Bitmap):void
{
      first.x = 230;
      first.y = 150;
      addChild(first);
      if(contains(second)) {        
           removeChild(second);
      }
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
Run Code Online (Sandbox Code Playgroud)