从更新返回到渲染

时间:2014-03-21 19:43:55

标签: java lwjgl slick2d

我正在尝试在SLick2D中创建一个基于状态的游戏,并且在尝试在同一个类中创建各种事件时遇到了困难。我想在屏幕上显示图像,当玩家点击时,图像会被另一个图像替换。

我不知道如何执行此操作,因为点击命令在'update'方法中,图像显示在'render'中。基本上,我不知道在使用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 个答案:

答案 0 :(得分:0)

首先,在你的渲染方法中,你打电话:

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

这样,每次调用渲染时都会创建新的Image对象。所以你需要做的是创建字段来保存你的图像并用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();
}

因此,不断调用update和render,这意味着你永远不必从一种方法“跳转”到另一种方法。