【问题标题】:AS3: can't addchild indexed movieclips into a spriteAS3:无法将子索引影片剪辑添加到精灵中
【发布时间】:2012-09-25 20:42:02
【问题描述】:

我在 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();

【问题讨论】:

  • 你是在问为什么会出现这个错误?
  • blockHolder.addChild(clonedSquare)之前,如果你trace(blockHolder),你会得到什么?

标签: actionscript-3 addchild


【解决方案1】:

好吧,我修正了错误。我仍然不清楚你的要求。基本上我将每个块添加到一个数组并以这种方式引用该块。您的 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();

【讨论】:

  • 非常感谢,它成功了!firstY 将计算乘以正方形高度(我使用的是 10px 正方形,这就是它出现在我的舞台上的原因)
  • 啊,明白了!是的,我使用的方块接近 100 像素。嗯,很酷,很高兴它在工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
相关资源
最近更新 更多