lundi 18 avril 2016

Displaying random image every 3 seconds - Android Studio

For some reason I can't seem to get this correct. What I wish to do is have any of the three images appear every 3 seconds but for some reason it gives me one random image and then another suddenly appears and disappears. So overall, I want it to generate an image every 3 seconds but can't get it to work for some reason. Below is the code for my VGameView:

public class VGameView extends View {
private Bitmap parrot;
private Bitmap moneyChest;
private Bitmap bomb;

Random randy;
int savedTime = 0;
long lastTime;
int rndImg;

private String score = "Score: ";
private int scoreCounter = 0;
private Paint scorePaint = new Paint();

public VGameView(Context context) {
    super(context);

    parrot = BitmapFactory.decodeResource(getResources(), R.drawable.parrot);

    moneyChest = BitmapFactory.decodeResource(getResources(), R.drawable.moneychest);

    bomb = BitmapFactory.decodeResource(getResources(), R.drawable.bomb);

    scorePaint.setColor(Color.BLACK);
    scorePaint.setTextSize(50);
}

public boolean onTouchEvent(MotionEvent event) {
    int eventAction = event.getAction();

    int x = (int) event.getX();
    int y = (int) event.getY();

    switch (eventAction) {
        case MotionEvent.ACTION_DOWN:
            break;
    }
    invalidate();
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    String.valueOf(scoreCounter);
    canvas.drawText(score + scoreCounter, 10, 100, scorePaint);

    long now = System.currentTimeMillis();
    savedTime += now - lastTime;
    lastTime = now;

    if (savedTime > 3000) {
        savedTime = 0;
        Random randy = new Random();
        rndImg = (int) (3 * Math.random()) + 1;
        if (rndImg == 1) {
            canvas.drawBitmap(parrot, 200, 500, null);
        }

        if (rndImg == 2) {
            canvas.drawBitmap(moneyChest, 600, 200, null);
        }

        if (rndImg == 3) {
            canvas.drawBitmap(bomb, 30, 30, null);
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire