突破项目将所有砖块涂在彼此之上

时间:2017-05-18 22:33:21

标签: javascript java android android-studio breakout

我在android studio编写一个突破游戏。我已经在一个数组中设置了砖块并将它们设置为绘制。但是,所有的砖都是相互重叠的。

BreakoutView类提取:

private static final int rows = 5;
private static final int columns = 10;
private static final int brickHeight = 50;
private static final int brickWidth = 100;
int brickX = 0;
int brickY = 0;
int brickSpaces = 0;
private Sprite[] bricks;

public BreakoutView(Context context, AttributeSet attrs) {
    super(context, attrs);
    bricks = new Sprite[rows * columns];
    for (Sprite brick: bricks) {
        brick.setSize(brickWidth, brickHeight);
        brick.setLocation(brickX, brickY);
        brick.paint.setARGB(255,250,0,0);
    }
}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    for (Sprite brick : bricks) {
        for (int r = 0; r <= rows; r++) {
            brickY = brickHeight + brickSpaces;
            for (int c = 0; c <= columns; c++) {
                brickX = brickWidth + brickSpaces;
                brickSpaces = 10;
            }
        }
    }
}

Sprite类:

public class Sprite {

    public RectF rect = new RectF();
    public float dx = 0;
    public float dy = 0;
    public Paint paint = new Paint();

    public Sprite(float x, float y, float width, float height) {
        setLocation(x, y);
        setSize(width, height);
    }
}

1 个答案:

答案 0 :(得分:0)

这里有几个问题。

首先,您要创建一个空数组,然后循环遍历该数组中的所有(不存在的)对象。

其次,看起来您希望此代码控制砖块的位置:

for (Sprite brick : bricks) {
    for (int r = 0; r <= rows; r++) {
        brickY = brickHeight + brickSpaces;
        for (int c = 0; c <= columns; c++) {
            brickX = brickWidth + brickSpaces;
            brickSpaces = 10;
        }
    }
}

...除了它不更新砖块对象本身的x和y。也许您忘了拨打brick.setLocation(brickX, brickY)

此外,您正在循环遍历所有砖块的所有位置。这意味着所有砖块都将获得循环产生的最后位置。

你的循环可能会这样:

for (Sprite brick : bricks) {
    // work out where this particular brick goes (rather than loop through them all)
    brickX = ?;
    brickY = ?;

    // set the location into the sprite
    brick.setLocation(brickX, brickY);
}