我不知道为什么这个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);
}
Piece Class:
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;
}
}
答案 0 :(得分:0)
首先,您可以制作Piece
类extends 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()
维护位图链接,因此如果基本位图发生更改,则会更改图像。)