有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从更新返回到渲染

我试图在SLick2D中创建一个基于状态的游戏,在尝试在同一个类中创建各种事件时遇到了困难。我想在屏幕上显示一个图像,当播放器单击时,图像将被另一个图像替换

我不知道怎么做,因为点击的命令在“更新”方法中,图像显示在“渲染”中。所以基本上,我不知道在使用update方法之后如何返回到render方法。 这是我试图做的一个假象。我还是不知道怎么做

private int a = 0;

public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
Image a = new Image("blabla"); //create 2 images
Image b = new Image("blabla");
if (a==0){            //when a=0 draw the first image
g.drawImage(a,0,0);
}
if (a==1){          //when a=1 draw another image, but only after mouse is clicked (a is changed to 1 when mouse is clicked in update method)
g.drawImage(b,0,0);
}


public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{  
Input input = gc.getInput();
int xpos = Mouse.getX();//222
int ypos = Mouse.getY();

if((xpos>00 && xpos<50) && (ypos>0 && ypos<222)){ // when user clicks set a to 1
        if(input.isMouseButtonDown(0)){
            a++;
            somehow return to render method;
        }

PS 这是我在Java的第一年,所以不要嘲笑我,使用复杂的术语:)


共 (1) 个答案

  1. # 1 楼答案

    首先,在渲染方法中,调用:

    Image a = new Image("blabla"); //create 2 images
    Image b = new Image("blabla");
    

    这样,每次调用渲染时都可以创建新的图像对象。因此,您需要做的是创建字段来保存图像,并在init(...)方法中初始化它们。下面是一个例子:

    public class TestGame extends StateBasedGame {
    
        Image a;
        Image b;
    
        public void init(GameContainer container, StateBasedGame game) 
                throws SlickException {
            a = new Image("blabla1.png");
            b = new Image("blabla2.png");
        }
    
        public void update(GameContainer container,
                           StateBasedGame game,
                           int delta) throws SlickException {
            // Put your update stuff here
        }
    
        public void render(GameContainer container,
                           StateBasedGame game,
                           Graphics g) throws SlickException {
            if (a == 0) {
                g.drawImage(a, 0, 0);
            } else if (a == 1) {
                g.drawImage(b, 0, 100);
            }
        }
    }
    

    现在回到问题上来,您不必担心“返回渲染”,因为更新和渲染有点像无限游戏循环中的助手方法。因此,在更新或渲染中更改的内容将在其中一个中看到(除非更改局部变量)。下面是游戏循环的大致伪表示:

    while (!gameCloseRequested) {
        update();
        render();
    }
    

    因此,更新和渲染是连续调用的,这意味着您永远不必从一个方法“跳转”到另一个方法