AS3:无法将子索引的动画片段添加到精灵中

时间:2012-10-04 18:34:16

标签: actionscript-3 addchild

我在flash(AS3)中创建一个动态阻挡地形,一切顺利,地形正确放置。但我需要包含碰撞,我希望块在动画片段(精灵)中,所以我可以测试与地形本身的碰撞。

Ps:我不知道单独测试每个块的碰撞是否合适,因为我将使用enterframe函数并且块生成是动态的。

我面临的问题是我有一个名为blockHolder的精灵,但是我无法将块添加到其中。

这是代码(我简化了代码,因此如果你直接将它们添加到舞台中,我们就会以级联方式创建块,例如 addChild(clonedSquare)

我收到的错误: TypeError:错误#1009:无法访问空对象引用的属性或方法。

var blockHolder:Sprite = new Sprite();

var clonedSquare = new square();

var lowestPoint:int = 10;
var highestPoint:int = 20;
var areaLenght:int = 10;

function createLvl():void
{
    for (var i:Number = 0; i<(areaLenght); i++)
    {
        clonedSquare = new square();
        clonedSquare.x = i * clonedSquare.width;
        //sets the height of the first block
        if (i == 0)
        {
            var firstY:Number = Math.ceil(Math.random()*((lowestPoint-highestPoint))+highestPoint)*clonedSquare.height;
            clonedSquare.y = firstY;
            trace("terrain begins " + firstY + " px down");
        }
        else
        {
                var previousId:Number = i - 1;
                clonedSquare.y = getChildByName("newSquare"+previousId).y + clonedSquare.height;
        }
        //sets the entity (block) name based on the iteration
        clonedSquare.name = "newSquare" + i;
        //adds the cloned square
        blockHolder.addChild(clonedSquare);
    }
    addChild(blockHolder);
}

createLvl();

1 个答案:

答案 0 :(得分:0)

我修好了错误。我还不清楚你要求的是什么。基本上我将每个块添加到一个数组并以这种方式引用该块。您的clonedSquare.y = getChildByName("newSquare"+previousId).y + clonedSquare.height;引发了错误。你的firstY也是第一个阻挡我的舞台,所以我把它设置为0作为firstY

var blockHolder:Sprite  = new Sprite();
var squares:Array       = [];
var lowestPoint:int     = 10;
var highestPoint:int    = 20;
var areaLenght:int      = 10;

function createLvl():void
{
    for (var i:Number = 0; i<(areaLenght); i++)
    {
        var clonedSquare = new square();
        clonedSquare.x = i * clonedSquare.width;
        if (i == 0)
        {
            var firstY:Number = Math.ceil(Math.random()*((lowestPoint-highestPoint))+highestPoint)*clonedSquare.height;
            //clonedSquare.y = firstY;
            clonedSquare.y = 0;
            trace("terrain begins " + firstY + " px down");
        }
        else
        {
            clonedSquare.y = squares[i - 1].y + clonedSquare.height;
        }
        blockHolder.addChild(clonedSquare);
        squares.push(clonedSquare);
    }
    addChild(blockHolder);
}
createLvl();