سؤال

I am trying to draw an image over another image when a user touches the screen. But the image only appears when the user touches and then disappears when they let go of the screen.

This is my if method:

int RED = 0;
int GREEN = 1;
Graphics g = game.getGraphics();
int len = touchEvents.size();

if (RED == 0) {
    ready = Assets.readybtntwo;
}

for(int i = 0; i < len; i++) {
    TouchEvent event = touchEvents.get(i);

    if(event.type == TouchEvent.TOUCH_UP){
        updateWaiting(touchEvents);
        RED +=1;

        if (RED == 0)
            ready = Assets.readybtntwo;

        if(RED == 1)
            ready = Assets.readybtngreentwo;
    }

    g.drawPixmap(ready, 0, 0);
}

Sorry I'm using a framework built from the book beginning android games. But it shouldn't matter, I want the image to stay forever and terminate the if loop.

هل كانت مفيدة؟

المحلول

You have a logic error here. It looks like the variable RED is local to your method if the above code is all inside the touch event handler. This means that when the user touches the screen each time it's reset to 0 and then becomes 1 again. This probably isn't what you want.

The reason that it's only rendered is that g.drawPixmap will either be submitting an element to a draw queue or rendering it immediately. This method to draw the button is only ever being drawn when you have a touch event!

Instead, you could have a boolean drawGreenReadyButton value as a class member, i.e.

private boolean drawGreenReadyButton = false;

Then you can change that inner if statement to the following:

if(event.type == TouchEvent.TOUCH_UP){
    updateWaiting(touchEvents);
    drawGreenReadyButton = true;
}

And inside your main rendering loop rather than in the touch event handler put:

if(drawGreenReadyButton) {
    g.drawPixmap(Assets.readybtngreentwo, 0, 0);
} else {
    g.drawPixmap(Assets.readybtntwo, 0, 0);
}

Also, consider using TouchEvent.TOUCH_DOWN rather than TouchEvent.TOUCH_UP, so that the button is shown green as soon as they touch the screen, not when they lift their finger up.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top