0

我不知道为什么这个 for 循环只显示我数组中的最后一个精灵。我对 AS3 有点陌生,想知道它为什么这样做:

private function loadComplete(event:Event):void {

var image:Bitmap = Bitmap(loader.content);

for (var i:int = 0; i <  4; i++ ) {
   var pB:BitmapData = new BitmapData(image.width / 2, image.height / 2, false, 0x000000FF);
    pB.copyPixels(image.bitmapData, new Rectangle(i * 20 , i * 20, image.width / 2, image.height / 2), new Point(0, 0));
    pieces.push(new Piece(new Sprite(), 0, 0));
    pieces[i].getSprite().graphics.beginBitmapFill(new Bitmap(pB.clone()).bitmapData, null, false);
    pieces[i].getSprite().graphics.drawRect(0, 0, image.width / 2, image.height / 2);
    pieces[i].getSprite().graphics.endFill();
    pieces[i].getSprite().addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
    pieces[i].getSprite().addEventListener(Event.ENTER_FRAME, dragPiece);

    addChild(pieces[i].getSprite());

       }
    stage.addEventListener(MouseEvent.MOUSE_UP, upHandler);
    }

单品类:

public class Piece 
{
    private var pieceX:int;
    private var pieceY:int;
    private var sprite:Sprite;

    public function Piece(sprite:Sprite, pieceX:int, pieceY:int):void 
    {
        this.sprite = sprite;
        this.pieceX = pieceX;
        this.pieceY = pieceY;
    }

    public function getSprite():Sprite {
        return sprite;
    }

}
4

1 回答 1

0

首先,您可以制作您的Pieceextends Sprite,并使用 Sprite 的功能,而无需那种丑陋的getSprite()构造,只需超过一块。

public class Piece extends Sprite {
    private var pieceX:int=0;
    private var pieceY:int=0;
    public function Piece(pieceX:int=0,pieceY:int=0) {
        this.pieceX = pieceX;
        this.pieceY = pieceY;
    }
    ...
}

然后,为了看到不止一个单件,您必须更改精灵的 X 和 Y 属性,否则它们确实是一个叠放的。

for (var i:int = 0; i <  4; i++ ) {
    var pB:BitmapData = new BitmapData(image.width / 2, image.height / 2, false, 0x000000FF);
    pB.copyPixels(image.bitmapData, new Rectangle(i * 20 , i * 20, image.width / 2, image.height / 2), new Point(0, 0));
    var piece:Piece=new Piece(0,0);
    pieces.push(piece);
    piece.graphics.beginBitmapFill(pB.clone(), null, false);
    piece.graphics.drawRect(0, 0, image.width / 2, image.height / 2);
    piece.graphics.endFill();
    piece.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
    piece.addEventListener(Event.ENTER_FRAME, dragPiece);

    addChild(piece);
    // here, add "piece.x=" and "piece.y=" assignments with correct values. For example
    piece.x=Math.random()*(stage.stageWidth-piece.width);
    piece.y=math.random()*(stage.stageHeight-piece.height);

}

另外,为什么要通过创建 Bitmap 对象来克隆该位图?pB.clone()工作没有任何问题。(刚刚尝试pB并发现beginBitmapFill()维护位图链接,因此如果基本位图发生更改,则会更改图像。)

于 2013-04-24T11:50:39.637 回答