Search code examples
androidanimationcanvasrefreshinvalidation

Update Canvas Animation


I don't need an answer any more!

I created an app and there should be bubbles bouncing around the screen. Everything is working, but they're not being drawn live.

Here the code (not ALL the code, but the important code):

The Bubble Class:

public class Bubble{

    private int ID;

    private float coordX;
    private float coordY;
    private float velX;
    private float velY;
    private float radius;

    private int color;

    private boolean popped;
    private boolean alive;
    private boolean dead;

    public Bubble(int coordX, int coordY, int velocityX, int velocityY, int ID, int color) {
        this.coordX = coordX;
        this.coordY = coordY;
        this.velX = velocityX;
        this.velY = velocityY;
        this.radius = 30;
        this.ID = ID;
        this.color = color;

        this.alive = true;
    }

    public void drawMe(Paint paint, Canvas canvas) {
        int paintStartColor = paint.getColor();
        paint.setColor(this.color);
        canvas.drawCircle(this.coordX, this.coordY, radius, paint);
        paint.setColor(paintStartColor);
        Log.d("Bubble","drawn bubble [" + ID + "] at (" + this.coordX + "|" + this.coordY + ")");
    }

    public void update() {

        //damit die bubble am rand anstößt und zurück prallt
        if(this.coordX - this.radius <= 0) this.velX = - this.velX;
        if(this.coordY - this.radius <= 0) this.velY = - this.velY;
        if(this.coordX + this.radius >= MainActivity.getInstance().getScreenSize().x) this.velX = - this.velX;
        if(this.coordY + this.radius >= MainActivity.getInstance().getScreenSize().y) this.velY = - this.velY;

        coordX += velX;
        coordY += velY;
        updateRadius();
//        Log.d("Bubble", "CoordX: " + coordX + ", velX: " + velX);
    }
}

The drawing method:

public void drawBubbles() {
    Paint paint = new Paint();
    for(Bubble b : bubbles) {
        b.drawMe(paint, MainActivity.getInstance().getCanvas());
    }
}

And the game loop:

while(this.isRunning()) {
      updateBubbles();   //update bubbles just calls the update() function in every bubble (for each loop)
      drawBubbles();
      //...sleep...
}

to draw all the bubbles, and it works, but I only see a difference, when I leave (not close!) the app and then go back into it. I call the method in a loop, and it is called 60 times per second, but why does it not appear on the screen? Also I can't invalidate the canvas.


Solution

  • I just misused the invalidate() method, so it worked fine after I fixed that.