0

我刚开始为班级制作一个非常简单的视频游戏,并且我有一个随机得分点生成器。此功能运行良好,没有任何问题,但是当我发布游戏并使用 Flashy Player 播放时,它会显示错误消息

错误 #2025:提供的 DisplayObject 必须是调用者的子对象。

由于程序在警报提示之外工作,所以我一直在关闭它,但我需要删除它。

function spawnscore()
{
    i = 0
    while (i == 0)
    {
        var pointy = Math.random()*640
        var pointx = Math.random()*747

        var pointcirc:warning = new warning();
        addChild(pointcirc);
        pointappearmusic.play();
        setTimeout(removepoint, 1500);
        pointcirc.addEventListener(MouseEvent.MOUSE_OVER, scoreclicked);

        function scoreclicked()
        {
            pointsound10.play();
            removeChild(pointcirc);
            score += 10;
            removeEventListener(MouseEvent.MOUSE_OVER, scoreclicked);
        }

        function removepoint()
        {
            // I'm pretty sure this is the problem
            removeChild(pointcirc);
        }

        pointcirc.x = pointx;
        pointcirc.y = pointy;
        break;
    }

    return;
}

我很确定我的问题出在 removepoint 函数中,但我不知道该怎么做。

编辑:突出显示错误

4

2 回答 2

1

该错误意味着您尝试DisplayObject从容器中删除 a 实际上不是该容器的子容器,因此看起来正在发生的事情是scoreclicked()运行并删除pointcirc,然后removepoint尝试再次删除它。

您只需要检查是否pointcirc已在 removepoint(). 有很多不同的方法可以做到这一点:您可以设置一个pointRemoved变量,或者pointcirc = null在它被删除后设置并检查它。您也可以直接使用 进行检查DisplayObjectContainer.contains(),或者只查看是否pointcirc.parent存在。

于 2013-03-05T00:08:53.787 回答
0

由于错误是无害的,您可以使用 try/catch 忽略它:

try
{
    removeChild(pointcirc);
}
catch(e:Error){}

我应该警告你,如果这while实际上是循环而不是break最后的 ing,你可能不会得到你期望的行为。

pointcircinremovepoint仅指返回pointcirc时的最后一个值spawnscore。那将是最后一个循环之后的值,这意味着每次removepoint调用时,它都试图删除最后一个pointcirc

您可以通过将循环中的代码放入闭包中来避免此问题:

function spawnscore()
{
    i = 0
    while (i == 0)
    {
        var pointy = Math.random()*640
        var pointx = Math.random()*747

        (function(pointcirc:warning)
        {
            var pointcirc:warning = new warning();
            addChild(pointcirc);
            pointappearmusic.play();

            var timeoutId:int = setTimeout(removepoint, 1500);

            pointcirc.addEventListener(MouseEvent.MOUSE_OVER, scoreclicked);

            function scoreclicked()
            {
                pointsound10.play();
                removeChild(pointcirc);
                score += 10;
                removeEventListener(MouseEvent.MOUSE_OVER, scoreclicked);
            }

            function removepoint()
            {
                clearTimeout(timeoutId);
                removeChild(pointcirc);
            }
        })(pointcirc);

        pointcirc.x = pointx;
        pointcirc.y = pointy;
        break;
    }

    return;
}

请参阅http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

于 2013-03-05T00:48:26.517 回答